示例#1
0
        public JintEngine()
        {
            PermissionSet = new PermissionSet(PermissionState.None);
            TypeSystem = new TypeSystem();

            _runtime = new JintRuntime(this);
        }
示例#2
0
 public Interpreter(TypeSystem typeSystem, MethodDefinition method)
 {
     this.ExternalMethods = new HashSet<MethodReference>();
     this.StaticFieldsSet = new HashSet<FieldDefinition>();
     this.typeSystem = typeSystem;
     this.method = method;
     this.typeEvaluator = new CodeTypeEvaluator(this.typeSystem, this.method);
 }
示例#3
0
 public ReferenceImporter(TableStream tableStreamBuffer, SignatureComparer signatureComparer)
 {
     if (tableStreamBuffer == null)
         throw new ArgumentNullException("tableStreamBuffer");
     _tableStreamBuffer = tableStreamBuffer;
     _signatureComparer = signatureComparer;
     _typeSystem = tableStreamBuffer.StreamHeader.MetadataHeader.TypeSystem;
 }
示例#4
0
 public void Initialize(TypeSystem system, ITypeSystemController controller)
 {
     TypeSystem = system;
     Controller = controller;
     Cache = new MetadataCache();
     Loader = new MetadataLoader(this);
     Resolver = new MetadataResolver(this);
 }
示例#5
0
 internal Checker(ErrorHandler errorHandler, TypeSystem typeSystem, TrivialHashtable scopeFor, // LJW: added scopeFor
     TrivialHashtable ambiguousTypes, TrivialHashtable referencedLabels)
     : base(errorHandler, typeSystem, scopeFor, ambiguousTypes, referencedLabels)
 {
     this.validChooses = new Hashtable();
     this.validMethodCalls = new Hashtable();
     this.validSetOperations = new Hashtable();
     this.validSelfAccess = new Hashtable();
 }
 protected override void Init(TypeSystem t, Node node, bool interProcedural, bool fixpoint, int maxDepth)
 {
     base.Init(t, node, interProcedural, fixpoint, maxDepth);
     factory = new ConsistentyElementFactory(this);
     if (ContractDeserializerContainer.ContractDeserializer == null)
     {
         IContractDeserializer cd = new Omni.Parser.ContractDeserializer();
         ContractDeserializerContainer.ContractDeserializer = cd;
     }
 }
        public static Expression GetDefaultValueExpression(this TypeReference typeReference, TypeSystem typeSystem)
        {
            if (typeReference.IsPrimitive)
            {
                string typeName = typeReference.FullName;

                switch (typeName)
                {
                    case "System.Boolean":
                        {
                            return new LiteralExpression(false, typeSystem, null);
                        }
                    case "System.Char":
                        {
                            return new LiteralExpression((char)0, typeSystem, null);
                        }
                    case "System.IntPtr":
                        {
                            return new DefaultObjectExpression(typeReference, null);
                        }
                    default:
                        {
                            return new LiteralExpression(Activator.CreateInstance(Type.GetType(typeName)), typeSystem, null);
                        }
                }
            }
            if (typeReference.IsGenericParameter)
            {
                return new DefaultObjectExpression(typeReference, null);
            }
            if (typeReference.IsArray)
            {
                //return GetLiteralExpression(typeReference.GetElementType(), typeSystem);
                return new LiteralExpression(null, typeSystem, null);
            }
            if (typeReference.IsValueType)
            {
                var typeDefinition = typeReference.Resolve();
                if (typeDefinition != null && typeDefinition.IsEnum)
                {
                    return new LiteralExpression(0, typeSystem, null);
                }
                else
                {
                    return new ObjectCreationExpression(typeReference.GetEmptyConstructorReference(), typeReference, null, null);
                }
            }
            if (typeReference.IsRequiredModifier)
            {
                RequiredModifierType typeReferenceAsReqMod = typeReference as RequiredModifierType;
                return typeReferenceAsReqMod.ElementType.GetDefaultValueExpression(typeSystem);
            }

            return new LiteralExpression(null, typeSystem, null);
        }
示例#8
0
 public Normalizer(TypeSystem typeSystem){
   this.typeSystem = typeSystem;
   this.exitTargets = new StatementList();
   this.continueTargets = new StatementList();
   this.currentTryStatements = new Stack();
   this.exceptionBlockFor = new TrivialHashtable();
   this.visitedCompleteTypes = new TrivialHashtable();
   this.EndIfLabel = new TrivialHashtable();
   this.foreachLength = 7;
   this.WrapToBlockExpression = true;
   this.useGenerics = TargetPlatform.UseGenerics;
 }
示例#9
0
 public Checker(ErrorHandler errorHandler, TypeSystem typeSystem, TrivialHashtable scopeFor, TrivialHashtable ambiguousTypes, TrivialHashtable referencedLabels)
   : base(errorHandler) {
   this.typeSystem = typeSystem;
   this.Errors = errorHandler == null ? null : errorHandler.Errors;
   this.scopeFor = scopeFor;
   this.ambiguousTypes = ambiguousTypes;
   this.referencedLabels = referencedLabels;
   this.MayNotReferenceThisFromFieldInitializer = true;
   this.allowedExceptions = new TypeNodeList();
   this.useGenerics = TargetPlatform.UseGenerics;
   this.AllowPropertiesIndexersAsRef = true;
 }
示例#10
0
        public Analyzer(TypeSystem t, Compilation c)
            : base(t, c)
        {
            if (c != null)
            {
                SpecSharpCompilerOptions ssco = c.CompilerParameters as SpecSharpCompilerOptions;
                if (ssco != null)
                {
                    if (ssco.Compatibility)
                        this.NonNullChecking = false; // i.e., turn it off if we need to be compatible
                    this.WeakPurityAnalysis = ssco.CheckPurity;
                    // Diego said it is important that the same instance of the purity analysis is used across all
                    // methods in the compilation unit. So create it here and just call it for each method in 
                    // the override for language specific analysis.
                    // PointsToAnalysis.verbose = true;
                    if (this.WeakPurityAnalysis)
                    {
                        
                        // InterProcedural bottom up traversal with fixpoint
                        //this.WeakPurityAnalyzer = new WeakPurityAndWriteEffectsAnalysis(this,typeSystem, c,true,true);
                        
                        // Only Intraprocedural (in this mode doesnot support delegates...)
                        //this.WeakPurityAnalyzer = new WeakPurityAndWriteEffectsAnalysis(this, typeSystem, c, false);
                        
                        // Interprocedural top-down inlining simulation (with max-depth)
                        this.WeakPurityAnalyzer = new WeakPurityAndWriteEffectsAnalysis(this, typeSystem, c, true,false,2);

                        this.WeakPurityAnalyzer.StandAloneApp = false;
                        this.WeakPurityAnalyzer.BoogieMode = true;
                    }
                    
                    /// Reentrancy ANALYSIS
                    
                    this.ObjectExposureAnalysis = false;
                    ObjectConsistencyAnalysis.verbose = false;
                    if (ObjectExposureAnalysis)
                    {
                        this.ObjectExposureAnalyzer = new ObjectExposureAnalysis(this, typeSystem, c, true, false, 4);
                    }
                    this.ReentrancyAnalysis = false;
                    if (ReentrancyAnalysis)
                    {
                        this.ReentrancyAnalyzer = new ReentrancyAnalysis(this, typeSystem, c, true, false, 4);
                    }
                    
                }
            }
        }
示例#11
0
    public void AddProgramVerifierPlugin(TypeSystem typeSystem, Compilation compilation){
#if Exp
      string boogieDir = System.Environment.GetEnvironmentVariable("BOOGIE");
      if (boogieDir == null)
        boogieDir = "C:\\boogie";
      string boogiePlugin = boogieDir + "\\Binaries\\BoogiePlugin.dll";
      string errorInfo = boogiePlugin + " (Set BOOGIE environment variable)";
#else
      string codebase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
      codebase = codebase.Replace("#", "%23");
      Uri codebaseUri = new Uri(codebase);
      Uri uri = new Uri(codebaseUri, "BoogiePlugin.dll");
      string boogiePlugin = uri.LocalPath;
      string errorInfo = boogiePlugin;
#endif
      this.AddPlugin(boogiePlugin, "Microsoft.Boogie.BoogiePlugin", "Microsoft.Boogie.BoogiePlugin from assembly " + errorInfo, typeSystem, compilation);
    }
        private static object Compile(string script)
        {
            var program = JintEngine.ParseProgram(script);

            if (program == null)
                return JsUndefined.Instance;

            var typeSystem = new TypeSystem();
            var scriptBuilder = typeSystem.CreateScriptBuilder(null);
            var bindingVisitor = new BindingVisitor(scriptBuilder);

            program.Accept(bindingVisitor);

            var boundProgram = bindingVisitor.Program;

            var interpreter = new JsonInterpreter(new JintEngine().Global);
            if (boundProgram.Body.Accept(interpreter))
                return interpreter.Result;

            return null;
        }
示例#13
0
 public Looker(Scope scope, ErrorHandler errorHandler, TrivialHashtable scopeFor, TypeSystem typeSystem, TrivialHashtable ambiguousTypes, TrivialHashtable referencedLabels)
   : base(errorHandler){
   //TODO: verify that crucial system types have either been imported or defined by the Parser
   this.scope = scope;
   this.AddToAllScopes(this.scope);
   this.scopeFor = scopeFor;
   this.ambiguousTypes = ambiguousTypes;
   this.referencedLabels = referencedLabels;
   this.alreadyReported = new TrivialHashtable();
   this.hasExplicitBaseClass = new TrivialHashtable();
   this.typesToKeepUninstantiated = new TrivialHashtable();
   this.UsedNamespaces = new UsedNamespaceList();
   this.targetFor = new TrivialHashtable();
   this.labelList = new IdentifierList();
   this.AbstractSealedUsedAsType = Error.NotAType;
   Debug.Assert(typeSystem != null);
   this.typeSystem = typeSystem;
   this.useGenerics = TargetPlatform.UseGenerics;
   this.inMethodParameter = false;
   this.inEventContext = false;
 }
示例#14
0
 public BuiltInTypes(TypeSystem typeSystem, MosaModule corlib)
 {
     Void = typeSystem.GetTypeByName(corlib, "System", "Void");
     Boolean = typeSystem.GetTypeByName(corlib, "System", "Boolean");
     Char = typeSystem.GetTypeByName(corlib, "System", "Char");
     I1 = typeSystem.GetTypeByName(corlib, "System", "SByte");
     U1 = typeSystem.GetTypeByName(corlib, "System", "Byte");
     I2 = typeSystem.GetTypeByName(corlib, "System", "Int16");
     U2 = typeSystem.GetTypeByName(corlib, "System", "UInt16");
     I4 = typeSystem.GetTypeByName(corlib, "System", "Int32");
     U4 = typeSystem.GetTypeByName(corlib, "System", "UInt32");
     I8 = typeSystem.GetTypeByName(corlib, "System", "Int64");
     U8 = typeSystem.GetTypeByName(corlib, "System", "UInt64");
     R4 = typeSystem.GetTypeByName(corlib, "System", "Single");
     R8 = typeSystem.GetTypeByName(corlib, "System", "Double");
     String = typeSystem.GetTypeByName(corlib, "System", "String");
     Object = typeSystem.GetTypeByName(corlib, "System", "Object");
     I = typeSystem.GetTypeByName(corlib, "System", "IntPtr");
     U = typeSystem.GetTypeByName(corlib, "System", "UIntPtr");
     TypedRef = typeSystem.GetTypeByName(corlib, "System", "TypedReference");
     Pointer = Void.ToUnmanagedPointer();
 }
    /// <summary>
    /// Standard check function, except that it returns a PreDAStatus data structure
    /// that contains the three tables mentioned above.
    /// </summary>
    /// <param name="t"></param>
    /// <param name="method"></param>
    /// <param name="analyzer"></param>
    /// <returns>A PreDAStatus data structure, or a null if error occurs. </returns>
    public static PreDAStatus Check(TypeSystem t, Method method, Analyzer analyzer) {
      Debug.Assert(method != null && analyzer != null);
      MethodReachingDefNNArrayChecker checker = new MethodReachingDefNNArrayChecker(t, analyzer, method);
      ControlFlowGraph cfg = analyzer.GetCFG(method);

      if (cfg == null)
        return null;

      InitializedVariables iv = new InitializedVariables(analyzer);
      NNArrayStatus status = new NNArrayStatus(iv);
      NNArrayStatus.Checker = checker;
      checker.Run(cfg, status);
      
      // Check whether there are arrays that have been created but not committed
      NNArrayStatus exitStatus2 = checker.exitState as NNArrayStatus;
      if (exitStatus2 != null) {
        if (Analyzer.Debug) {
          Console.WriteLine("exit state of {0} is", method.FullName);
          exitStatus2.Dump();
        }
        ArrayList notCommitted = exitStatus2.CreatedButNotInitedArrays();
        if (notCommitted != null && notCommitted.Count != 0) {
          foreach (object o in notCommitted) {
            string offendingString = "A non null element array";
            Node offendingNode = method;
            if (o is Variable) {
              offendingString = "Variable \'" + o + "\'";
              offendingNode = o as Variable;
            }
            if (o is Pair<Variable, Field>) {
              Pair<Variable, Field> pair = o as Pair<Variable, Field>;
              Variable var = pair.Fst;
              Field fld = pair.Snd;
              offendingString = "Field \'" + var + "." + fld + "\'";
              if (NNArrayStatus.FieldsToMB.ContainsKey(pair)) {
                offendingNode = NNArrayStatus.FieldsToMB[pair] as MemberBinding;
                if (offendingNode == null) {
                  offendingNode = fld;
                } else {
                  MemberBinding mb = offendingNode as MemberBinding;
                  if (mb.TargetObject == null || mb.SourceContext.SourceText == null) {
                    offendingNode = fld;
                  }
                }
              }
            }
            checker.HandleError(offendingNode, Error.ShouldCommit, offendingString);
          }
        }

        ArrayList notCommittedOnAllPaths = exitStatus2.CreatedButNotFullyCommittedArrays();
        if (notCommittedOnAllPaths != null && notCommittedOnAllPaths.Count != 0) {
          foreach (object o in notCommittedOnAllPaths) {
            string offendingString = "A non-null element array";
            Node offendingNode = method;
            if (o is Variable) {
              offendingString = "variable \'" + o + "\'";
              offendingNode = o as Variable;
            } else if (o is Pair<Variable, Field>) {
              Pair<Variable, Field> pair = o as Pair<Variable, Field>;
              Variable var = pair.Fst;
              Field fld = pair.Snd;
              if (NNArrayStatus.FieldsToMB.ContainsKey(pair)) {
                offendingNode = NNArrayStatus.FieldsToMB[pair] as MemberBinding;
                if (offendingNode == null) {
                  offendingNode = fld;
                } else {
                  MemberBinding mb = offendingNode as MemberBinding;
                  if (mb.TargetObject == null || mb.SourceContext.SourceText==null) {
                    offendingNode = fld;
                  }
                }
              }
              offendingString = "field \'" + var + "." + fld + "\'";
            }

            checker.HandleError(offendingNode, Error.ShouldCommitOnAllPaths, offendingString);
          }
        }
        if (checker.errors != null && checker.errors.Count != 0) {
          checker.HandleError();
          checker.errors.Clear();
          return null;
        }
      }
      return new PreDAStatus(checker.NotCommitted, checker.Committed, checker.OKTable, checker.NonDelayArrayTable);
    }
示例#16
0
        /// <summary>
        ///     Compiles a collection of Dynamo nodes into a function definition for a custom node.
        /// </summary>
        /// <param name="functionId"></param>
        /// <param name="returnKeys"></param>
        /// <param name="functionName"></param>
        /// <param name="funcBody"></param>
        /// <param name="outputNodes"></param>
        /// <param name="parameters"></param>
        /// <param name="verboseLogging"></param>
        internal void CompileCustomNodeDefinition(
            Guid functionId, IEnumerable <string> returnKeys, string functionName,
            IEnumerable <NodeModel> funcBody, IEnumerable <AssociativeNode> outputNodes,
            IEnumerable <TypedParameter> parameters, bool verboseLogging)
        {
            OnAstNodeBuilding(functionId);

            var functionBody = new CodeBlockNode();
            var asts         = CompileToAstNodes(funcBody, CompilationContext.None, verboseLogging);

            functionBody.Body.AddRange(asts.SelectMany(t => t.Item2));

            var outputs = outputNodes.ToList();

            if (outputs.Count > 1)
            {
                /* rtn_array = {};
                 * rtn_array[key0] = out0;
                 * rtn_array[key1] = out1;
                 * ...
                 * return = rtn_array;
                 */

                // return array, holds all outputs
                string rtnName = "__temp_rtn_" + functionId.ToString().Replace("-", String.Empty);
                functionBody.Body.Add(
                    AstFactory.BuildAssignment(
                        AstFactory.BuildIdentifier(rtnName),
                        AstFactory.BuildExprList(new List <string>())));

                // indexers for each output
                IEnumerable <AssociativeNode> indexers = returnKeys != null
                    ? returnKeys.Select(AstFactory.BuildStringNode) as IEnumerable <AssociativeNode>
                    : Enumerable.Range(0, outputs.Count).Select(AstFactory.BuildIntNode);

                functionBody.Body.AddRange(
                    outputs.Zip(
                        indexers,
                        (outputId, indexer) => // for each outputId and return key
                        // pack the output into the return array
                        AstFactory.BuildAssignment(AstFactory.BuildIdentifier(rtnName, indexer), outputId)));

                // finally, return the return array
                functionBody.Body.Add(AstFactory.BuildReturnStatement(AstFactory.BuildIdentifier(rtnName)));
            }
            else
            {
                // For single output, directly return that identifier or null.
                AssociativeNode returnValue = outputs.Count == 1 ? outputs[0] : new NullNode();
                functionBody.Body.Add(AstFactory.BuildReturnStatement(returnValue));
            }

            Type allTypes = TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var);

            //Create a new function definition
            var functionDef = new FunctionDefinitionNode
            {
                Name      = functionName.Replace("-", string.Empty),
                Signature =
                    new ArgumentSignatureNode
                {
                    Arguments =
                        parameters.Select(param => AstFactory.BuildParamNode(param.Name, param.Type)).ToList()
                },
                FunctionBody = functionBody,
                ReturnType   = allTypes
            };

            OnAstNodeBuilt(functionId, new[] { functionDef });
        }
示例#17
0
        /// <summary>
        ///     Compiles a collection of Dynamo nodes into a function definition for a custom node.
        /// </summary>
        /// <param name="functionId"></param>
        /// <param name="returnKeys"></param>
        /// <param name="functionName"></param>
        /// <param name="funcBody"></param>
        /// <param name="outputNodes"></param>
        /// <param name="parameters"></param>
        /// <param name="verboseLogging"></param>
        internal void CompileCustomNodeDefinition(
            Guid functionId, IEnumerable <string> returnKeys, string functionName,
            IEnumerable <NodeModel> funcBody, IEnumerable <AssociativeNode> outputNodes,
            IEnumerable <TypedParameter> parameters, bool verboseLogging)
        {
            OnAstNodeBuilding(functionId);

            var functionBody = new CodeBlockNode();
            var asts         = CompileToAstNodes(funcBody, CompilationContext.None, verboseLogging);

            functionBody.Body.AddRange(asts.SelectMany(t => t.Item2));

            var outputs = outputNodes.ToList();

            if (outputs.Count > 1)
            {
                /* rtn_dict = Dictionary.ByKeysValues({key0, ..., keyn}, {out0, ..., outn});
                 * return = rtn_dict;
                 */

                // return dictionary, holds all outputs
                string rtnName = "__temp_rtn_" + functionId.ToString().Replace("-", String.Empty);

                //// indexers for each output
                var indexers = returnKeys != null
                    ? returnKeys.Select(AstFactory.BuildStringNode) as IEnumerable <AssociativeNode>
                    : Enumerable.Range(0, outputs.Count).Select(AstFactory.BuildIntNode);

                // Create AST for Dictionary initialization
                var kvps = outputs.Zip(indexers, (outputId, indexer) =>
                                       new KeyValuePair <AssociativeNode, AssociativeNode>(indexer, outputId));
                var dict = new DictionaryExpressionBuilder();
                foreach (var kvp in kvps)
                {
                    dict.AddKey(kvp.Key);
                    dict.AddValue(kvp.Value);
                }
                functionBody.Body.Add(AstFactory.BuildAssignment(AstFactory.BuildIdentifier(rtnName), dict.ToFunctionCall()));

                // finally, return the return array
                functionBody.Body.Add(AstFactory.BuildReturnStatement(AstFactory.BuildIdentifier(rtnName)));
            }
            else
            {
                // For single output, directly return that identifier or null.
                AssociativeNode returnValue = outputs.Count == 1 && outputs[0] != null ? outputs[0] : new NullNode();
                functionBody.Body.Add(AstFactory.BuildReturnStatement(returnValue));
            }

            Type allTypes = TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var);

            //Create a new function definition
            var functionDef = new FunctionDefinitionNode
            {
                Name      = functionName.Replace("-", string.Empty),
                Signature =
                    new ArgumentSignatureNode
                {
                    Arguments =
                        parameters.Select(param => AstFactory.BuildParamNode(param.Name, param.Type)).ToList()
                },
                FunctionBody = functionBody,
                ReturnType   = allTypes
            };

            OnAstNodeBuilt(functionId, new[] { functionDef });
        }
示例#18
0
 public BinaryExpression(BinaryOperator @operator, Expression left, Expression right, TypeSystem typeSystem, bool isChecked, IEnumerable <Instruction> instructions, bool isOverridenOperation)
     : this(@operator, left, right, isChecked, instructions, isOverridenOperation)
 {
     this.typeSystem = typeSystem;
     UpdateType();
 }
示例#19
0
 private static IEnumerable <TypedParameter> GetUnaryFuncArgs()
 {
     return(new List <TypedParameter> {
         new TypedParameter("x", TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var)),
     });
 }
示例#20
0
        public void Optimize(DecompilerContext context, ILBlock method, ILAstOptimizationStep abortBeforeStep = ILAstOptimizationStep.None)
        {
            this.context    = context;
            this.typeSystem = context.CurrentMethod.Module.TypeSystem;
            this.method     = method;

            if (abortBeforeStep == ILAstOptimizationStep.RemoveRedundantCode)
            {
                return;
            }
            RemoveRedundantCode(method);

            if (abortBeforeStep == ILAstOptimizationStep.ReduceBranchInstructionSet)
            {
                return;
            }
            foreach (ILBlock block in method.GetSelfAndChildrenRecursive <ILBlock>())
            {
                ReduceBranchInstructionSet(block);
            }
            // ReduceBranchInstructionSet runs before inlining because the non-aggressive inlining heuristic
            // looks at which type of instruction consumes the inlined variable.

            if (abortBeforeStep == ILAstOptimizationStep.InlineVariables)
            {
                return;
            }
            // Works better after simple goto removal because of the following debug pattern: stloc X; br Next; Next:; ldloc X
            ILInlining inlining1 = new ILInlining(method);

            inlining1.InlineAllVariables();

            if (abortBeforeStep == ILAstOptimizationStep.CopyPropagation)
            {
                return;
            }
            inlining1.CopyPropagation();

            if (abortBeforeStep == ILAstOptimizationStep.YieldReturn)
            {
                return;
            }
            YieldReturnDecompiler.Run(context, method);

            if (abortBeforeStep == ILAstOptimizationStep.PropertyAccessInstructions)
            {
                return;
            }
            IntroducePropertyAccessInstructions(method);

            if (abortBeforeStep == ILAstOptimizationStep.SplitToMovableBlocks)
            {
                return;
            }
            foreach (ILBlock block in method.GetSelfAndChildrenRecursive <ILBlock>())
            {
                SplitToBasicBlocks(block);
            }

            if (abortBeforeStep == ILAstOptimizationStep.TypeInference)
            {
                return;
            }
            // Types are needed for the ternary operator optimization
            TypeAnalysis.Run(context, method);

            foreach (ILBlock block in method.GetSelfAndChildrenRecursive <ILBlock>())
            {
                bool modified;
                do
                {
                    modified = false;

                    if (abortBeforeStep == ILAstOptimizationStep.SimplifyShortCircuit)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(new SimpleControlFlow(context, method).SimplifyShortCircuit);

                    if (abortBeforeStep == ILAstOptimizationStep.SimplifyTernaryOperator)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(new SimpleControlFlow(context, method).SimplifyTernaryOperator);

                    if (abortBeforeStep == ILAstOptimizationStep.SimplifyNullCoalescing)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(new SimpleControlFlow(context, method).SimplifyNullCoalescing);

                    if (abortBeforeStep == ILAstOptimizationStep.JoinBasicBlocks)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(new SimpleControlFlow(context, method).JoinBasicBlocks);

                    if (abortBeforeStep == ILAstOptimizationStep.SimplifyLogicNot)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(SimplifyLogicNot);

                    if (abortBeforeStep == ILAstOptimizationStep.SimplifyShiftOperators)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(SimplifyShiftOperators);

                    if (abortBeforeStep == ILAstOptimizationStep.TypeConversionSimplifications)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(TypeConversionSimplifications);

                    if (abortBeforeStep == ILAstOptimizationStep.SimplifyLdObjAndStObj)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(SimplifyLdObjAndStObj);

                    if (abortBeforeStep == ILAstOptimizationStep.SimplifyCustomShortCircuit)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(new SimpleControlFlow(context, method).SimplifyCustomShortCircuit);

                    if (abortBeforeStep == ILAstOptimizationStep.SimplifyLiftedOperators)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(SimplifyLiftedOperators);

                    if (abortBeforeStep == ILAstOptimizationStep.TransformArrayInitializers)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(TransformArrayInitializers);

                    if (abortBeforeStep == ILAstOptimizationStep.TransformMultidimensionalArrayInitializers)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(TransformMultidimensionalArrayInitializers);

                    if (abortBeforeStep == ILAstOptimizationStep.TransformObjectInitializers)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(TransformObjectInitializers);

                    if (abortBeforeStep == ILAstOptimizationStep.MakeAssignmentExpression)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(MakeAssignmentExpression);
                    modified |= block.RunOptimization(MakeCompoundAssignments);

                    if (abortBeforeStep == ILAstOptimizationStep.IntroducePostIncrement)
                    {
                        return;
                    }
                    modified |= block.RunOptimization(IntroducePostIncrement);

                    if (abortBeforeStep == ILAstOptimizationStep.InlineExpressionTreeParameterDeclarations)
                    {
                        return;
                    }
                    if (context.Settings.ExpressionTrees)
                    {
                        modified |= block.RunOptimization(InlineExpressionTreeParameterDeclarations);
                    }

                    if (abortBeforeStep == ILAstOptimizationStep.InlineVariables2)
                    {
                        return;
                    }
                    modified |= new ILInlining(method).InlineAllInBlock(block);
                    new ILInlining(method).CopyPropagation();
                } while(modified);
            }

            if (abortBeforeStep == ILAstOptimizationStep.FindLoops)
            {
                return;
            }
            foreach (ILBlock block in method.GetSelfAndChildrenRecursive <ILBlock>())
            {
                new LoopsAndConditions(context).FindLoops(block);
            }

            if (abortBeforeStep == ILAstOptimizationStep.FindConditions)
            {
                return;
            }
            foreach (ILBlock block in method.GetSelfAndChildrenRecursive <ILBlock>())
            {
                new LoopsAndConditions(context).FindConditions(block);
            }

            if (abortBeforeStep == ILAstOptimizationStep.FlattenNestedMovableBlocks)
            {
                return;
            }
            FlattenBasicBlocks(method);

            if (abortBeforeStep == ILAstOptimizationStep.RemoveEndFinally)
            {
                return;
            }
            RemoveEndFinally(method);

            if (abortBeforeStep == ILAstOptimizationStep.RemoveRedundantCode2)
            {
                return;
            }
            RemoveRedundantCode(method);

            if (abortBeforeStep == ILAstOptimizationStep.GotoRemoval)
            {
                return;
            }
            new GotoRemoval().RemoveGotos(method);

            if (abortBeforeStep == ILAstOptimizationStep.DuplicateReturns)
            {
                return;
            }
            DuplicateReturnStatements(method);

            if (abortBeforeStep == ILAstOptimizationStep.GotoRemoval2)
            {
                return;
            }
            new GotoRemoval().RemoveGotos(method);

            if (abortBeforeStep == ILAstOptimizationStep.ReduceIfNesting)
            {
                return;
            }
            ReduceIfNesting(method);

            if (abortBeforeStep == ILAstOptimizationStep.InlineVariables3)
            {
                return;
            }
            // The 2nd inlining pass is necessary because DuplicateReturns and the introduction of ternary operators
            // open up additional inlining possibilities.
            new ILInlining(method).InlineAllVariables();

            if (abortBeforeStep == ILAstOptimizationStep.CachedDelegateInitialization)
            {
                return;
            }
            foreach (ILBlock block in method.GetSelfAndChildrenRecursive <ILBlock>())
            {
                for (int i = 0; i < block.Body.Count; i++)
                {
                    // TODO: Move before loops
                    CachedDelegateInitializationWithField(block, ref i);
                    CachedDelegateInitializationWithLocal(block, ref i);
                }
            }

            if (abortBeforeStep == ILAstOptimizationStep.IntroduceFixedStatements)
            {
                return;
            }
            // we need post-order traversal, not pre-order, for "fixed" to work correctly
            foreach (ILBlock block in TreeTraversal.PostOrder <ILNode>(method, n => n.GetChildren()).OfType <ILBlock>())
            {
                for (int i = block.Body.Count - 1; i >= 0; i--)
                {
                    // TODO: Move before loops
                    if (i < block.Body.Count)
                    {
                        IntroduceFixedStatements(block.Body, i);
                    }
                }
            }

            if (abortBeforeStep == ILAstOptimizationStep.RecombineVariables)
            {
                return;
            }
            RecombineVariables(method);

            if (abortBeforeStep == ILAstOptimizationStep.TypeInference2)
            {
                return;
            }
            TypeAnalysis.Reset(method);
            TypeAnalysis.Run(context, method);

            if (abortBeforeStep == ILAstOptimizationStep.RemoveRedundantCode3)
            {
                return;
            }
            GotoRemoval.RemoveRedundantCode(method);

            // ReportUnassignedILRanges(method);
        }
示例#21
0
        /// <summary>
        /// array[index1][index2][...][indexN] = value, and
        /// indices = {index1, index2, ..., indexN}
        /// </summary>
        public StackValue SetValueForIndices(List <StackValue> indices, StackValue value, RuntimeCore runtimeCore)
        {
            var zippedIndices = ArrayUtils.GetZippedIndices(indices, runtimeCore);

            if (zippedIndices == null || zippedIndices.Length == 0)
            {
                return(StackValue.Null);
            }

            var t = TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var);

            if (zippedIndices.Length == 1)
            {
                var coercedData = TypeSystem.Coerce(value, t, runtimeCore);
                return(SetValueForIndices(zippedIndices[0], coercedData, runtimeCore));
            }

            if (value.IsArray)
            {
                // Replication happens on both side.
                var dataElements = heap.ToHeapObject <DSArray>(value);
                var length       = Math.Min(zippedIndices.Length, dataElements.Count);

                var oldValues = new StackValue[length];
                for (int i = 0; i < length; ++i)
                {
                    var coercedData = TypeSystem.Coerce(dataElements.GetValueAt(i), t, runtimeCore);
                    oldValues[i] = SetValueForIndices(zippedIndices[i], coercedData, runtimeCore);
                }

                // The returned old values shouldn't have any key-value pairs
                try
                {
                    return(heap.AllocateArray(oldValues));
                }
                catch (RunOutOfMemoryException)
                {
                    runtimeCore.RuntimeStatus.LogWarning(WarningID.RunOutOfMemory, Resources.RunOutOfMemory);
                    return(StackValue.Null);
                }
            }
            else
            {
                // Replication is only on the LHS, so collect all old values
                // and return them in an array.
                var coercedData = TypeSystem.Coerce(value, t, runtimeCore);
                var oldValues   = new StackValue[zippedIndices.Length];
                for (int i = 0; i < zippedIndices.Length; ++i)
                {
                    oldValues[i] = SetValueForIndices(zippedIndices[i], coercedData, runtimeCore);
                }

                // The returned old values shouldn't have any key-value pairs
                try
                {
                    return(heap.AllocateArray(oldValues));
                }
                catch (RunOutOfMemoryException)
                {
                    runtimeCore.RuntimeStatus.LogWarning(WarningID.RunOutOfMemory, Resources.RunOutOfMemory);
                    return(StackValue.Null);
                }
            }
        }
示例#22
0
        public StackValue CopyArray(RuntimeCore runtimeCore)
        {
            var anyType = TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var, Constants.kArbitraryRank);

            return(CopyArray(anyType, runtimeCore));
        }
示例#23
0
        public static JSExpression CastToEnumType(JSExpression value, TypeReference type, TypeSystem typeSystem)
        {
            if (IsNullableEnum(type))
            {
                // Handle casts like <int> -> <Enum?> by doing a two stage cast:
                // <int> -> <Enum> -> <Enum?>
                // Issue #154

                var git    = (GenericInstanceType)type;
                var casted = JSCastExpression.New(
                    value, git.GenericArguments[0], typeSystem, true
                    );
                var coerced = JSChangeTypeExpression.New(
                    casted, type, typeSystem
                    );
                return(coerced);
            }
            else
            {
                return(JSCastExpression.New(
                           value, type, typeSystem, true
                           ));
            }
        }
示例#24
0
 internal static bool TypeOrElementTypeIsEntity(Type type)
 {
     type = TypeSystem.GetElementType(type);
     type = Nullable.GetUnderlyingType(type) ?? type;
     return(!PrimitiveType.IsKnownType(type) && (GetKeyPropertiesOnType(type) != null));
 }
 public SimpleVariableInliner(TypeSystem typeSystem)
 {
     base();
     this.typeSystem = typeSystem;
     return;
 }
示例#26
0
        public static Expression GetDefaultValueExpression(this TypeReference typeReference, TypeSystem typeSystem)
        {
            if (typeReference.IsPrimitive)
            {
                string typeName = typeReference.FullName;

                switch (typeName)
                {
                case "System.Boolean":
                {
                    return(new LiteralExpression(false, typeSystem, null));
                }

                case "System.Char":
                {
                    return(new LiteralExpression((char)0, typeSystem, null));
                }

                case "System.IntPtr":
                {
                    return(new DefaultObjectExpression(typeReference, null));
                }

                default:
                {
                    return(new LiteralExpression(Activator.CreateInstance(Type.GetType(typeName)), typeSystem, null));
                }
                }
            }
            if (typeReference.IsGenericParameter)
            {
                return(new DefaultObjectExpression(typeReference, null));
            }
            if (typeReference.IsArray)
            {
                //return GetLiteralExpression(typeReference.GetElementType(), typeSystem);
                return(new LiteralExpression(null, typeSystem, null));
            }
            if (typeReference.IsValueType)
            {
                var typeDefinition = typeReference.Resolve();
                if (typeDefinition != null && typeDefinition.IsEnum)
                {
                    return(new LiteralExpression(0, typeSystem, null));
                }
                else
                {
                    return(new ObjectCreationExpression(typeReference.GetEmptyConstructorReference(), typeReference, null, null));
                }
            }
            if (typeReference.IsRequiredModifier)
            {
                RequiredModifierType typeReferenceAsReqMod = typeReference as RequiredModifierType;
                return(typeReferenceAsReqMod.ElementType.GetDefaultValueExpression(typeSystem));
            }

            return(new LiteralExpression(null, typeSystem, null));
        }
示例#27
0
        public virtual ExpressionSyntax Constant(object value, Stencil stencil, Type generatedType = null)
        {
            switch (value)
            {
            case float f:
                return(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(f)));

            case decimal d:
                return(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(d)));

            case int i:
                return(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(i)));

            case double d:
                return(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(d)));

            case bool b:
                return(LiteralExpression(b ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression));

            case string s:
                return(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(s)));

            case char c:
                return(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(c)));

            case Vector2 _:
            case Vector3 _:
            case Vector4 _:
            case Quaternion _:
            case Color _:

                if (generatedType == null)
                {
                    generatedType = value.GetType();
                }
                return(RoslynBuilder.CreateConstantInitializationExpression(value, generatedType));

            case Enum _:
                return(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                              IdentifierName(value.GetType().Name),
                                              IdentifierName(value.ToString())
                                              ));

            case EnumValueReference e:
                return(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                              TypeSystem.BuildTypeSyntax(e.EnumType.Resolve(stencil)),
                                              IdentifierName(e.ValueAsEnum(stencil).ToString())
                                              ));

            case AnimationCurve _:
                return(DefaultExpression(TypeSyntaxFactory.ToTypeSyntax(typeof(AnimationCurve))));

            case LayerMask m:
                return(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(m.value)));

            case InputName inputName:
                return(inputName.name == null
                        ? LiteralExpression(SyntaxKind.NullLiteralExpression)
                        : LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(inputName.name)));

            case SceneAsset asset:
                return(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(AssetDatabase.GetAssetPath(asset))));

            default:
                return(DefaultExpression(TypeSystem.BuildTypeSyntax(value.GetType())));
            }
        }
 public void AssignFieldAddress(Variable dest, Field field, Variable source, Method currentMethod, TypeSystem typeSystem) {
   // We capture the correct field address only when necessary. Currently, if the field is a non-static
   // struct field, or if we are in the constructor and the field is a non-null field assigned on this.
   if (!field.IsStatic && field.Type != null)
   {
     field = CanonicalField(field);
     ISymValue objectLoc = this.egraph[ValueOf, this.egraph[source]];
     DefAssignLattice.AVal sourceAVal = (DefAssignLattice.AVal)this.egraph[objectLoc];
     ISymValue fieldLoc = this.egraph[field, objectLoc];
     this.egraph[ValueOf, this.egraph[dest]] = fieldLoc;
     // check if objectLoc is fully assigned. If so, set fieldLoc as assigned too.
     if (this.IsAssigned(objectLoc)) {
       this.egraph[fieldLoc] = DefAssignLattice.AVal.AssignedNoDelay;
     }
     // existential delay
     else if (!sourceAVal.IsBottom && !sourceAVal.IsNotDelayed)
     {
       this.egraph[fieldLoc] = ((DefAssignLattice.AVal)this.egraph[fieldLoc]).SameButWith(sourceAVal.Delay);
     }
     // end existential delay
     else
     {
       SetDelay(fieldLoc, DefAssignLattice.Delay.NoDelay);
     }
   }
   else {
     if (source != null) {
       this.SetAssignedAndCopyDelay(dest, source);
     }
     else {
       this.SetLocationAssigned(dest);
       this.SetAssignedRef(dest);
     }
   }
 }
示例#29
0
        internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms())
        {
            ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing);
            ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset);
            ThrowUnsupportedIfKeywordSet(KEY.Context_Connection);
            ThrowUnsupportedIfKeywordSet(KEY.Enlist);
            ThrowUnsupportedIfKeywordSet(KEY.TransactionBinding);

            // Network Library has its own special error message
            if (ContainsKey(KEY.Network_Library))
            {
                throw SQL.NetworkLibraryKeywordNotSupported();
            }

            _integratedSecurity = ConvertValueToIntegratedSecurity();
#if MANAGED_SNI
            if(_integratedSecurity)
            {
                throw SQL.UnsupportedKeyword(KEY.Integrated_Security);
            }
#endif
            _encrypt = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt);
            _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS);
            _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info);
            _pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling);
            _replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication);
            _userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance);
            _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover);

            _connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout);
            _loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout);
            _maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size);
            _minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size);
            _packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size);
            _connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count);
            _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval);

            _applicationIntent = ConvertValueToApplicationIntent();
            _applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name);
            _attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename);
            _currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language);
            _dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source);
            _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
            _failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner);
            _initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog);
            _password = ConvertValueToString(KEY.Password, DEFAULT.Password);
            _trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate);

            // Temporary string - this value is stored internally as an enum.
            string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null);

            _userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID);
            _workstationId = ConvertValueToString(KEY.Workstation_Id, null);



            if (_loadBalanceTimeout < 0)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout);
            }

            if (_connectTimeout < 0)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout);
            }

            if (_maxPoolSize < 1)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size);
            }

            if (_minPoolSize < 0)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size);
            }
            if (_maxPoolSize < _minPoolSize)
            {
                throw ADP.InvalidMinMaxPoolSizeValues();
            }

            if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize))
            {
                throw SQL.InvalidPacketSizeValue();
            }


            ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name);
            ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language);
            ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
            ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner);
            ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog);
            ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password);
            ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID);
            if (null != _workstationId)
            {
                ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id);
            }

            if (!String.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase))
            {
                // fail-over partner is set

                if (_multiSubnetFailover)
                {
                    throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null);
                }

                if (String.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase))
                {
                    throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog);
                }
            }

            if (0 <= _attachDBFileName.IndexOf('|'))
            {
                throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename);
            }
            else
            {
                ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename);
            }


            if (true == _userInstance && !string.IsNullOrEmpty(_failoverPartner))
            {
                throw SQL.UserInstanceFailoverNotCompatible();
            }

            if (string.IsNullOrEmpty(typeSystemVersionString))
            {
                typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion;
            }

            if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.Latest;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2000;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2005;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2008;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2012;
            }
            else
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version);
            }


            if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner))
                throw SQL.ROR_FailoverNotSupportedConnString();

            if ((_connectRetryCount < 0) || (_connectRetryCount > 255))
            {
                throw ADP.InvalidConnectRetryCountValue();
            }

            if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60))
            {
                throw ADP.InvalidConnectRetryIntervalValue();
            }
        }
示例#30
0
        public override object Execute(Expression expression)
        {
            var state = Translate(expression);

            // Perform local indexing if needed
            if (Configuration.GenerateIndexYAMLFile)
            {
                BuildIndex(state);
            }

            // Build a query
            var datastore = new Google.Apis.Datastore.v1beta3.DatastoreService(Authenticator.GetInitializer());
            var dict      = state.Parameters.ToDictionary(x => x.ParameterName, parameter => new GqlQueryParameter()
            {
                Value = ReadQuery_ConvertTypeToValueType(parameter.ParameterName, parameter.Value, parameter.TypeCode)
            });
            var gql = new GqlQuery
            {
                QueryString   = state.QueryBuilder.ToString(),
                AllowLiterals = false, // enforce parameterized queries
                NamedBindings = dict

                                //NameArgs = state.Parameters.Select(x => new GqlQueryArg { Name = x.ParameterName,
                                //    Value = ReadQuery_ConvertTypeToValueType(x.ParameterName, x.Value, x.TypeCode) }).ToList()
            };

            // Grab results
            var result = datastore.Projects.RunQuery(new RunQueryRequest
            {
                GqlQuery = gql
            }, Authenticator.GetProjectId()).Execute();

            // Project if necessary / Select() method
            if (state.Projector != null)
            {
                var elementType = TypeSystem.GetElementType(expression.Type);
                var projector   = state.Projector.Compile();

                return(Activator.CreateInstance(
                           typeof(ProjectionReader <>).MakeGenericType(elementType),
                           BindingFlags.Instance | BindingFlags.NonPublic, null,
                           new object[] { result.Batch.EntityResults.Select(x => x.Entity), projector },
                           null
                           ));
            }

            // First()/Single() method
            if (state.QueryState.HasFlag(QueryState.IsFirst) || state.QueryState.HasFlag(QueryState.IsSingle))
            {
                if (result.Batch.EntityResults.Count == 0 && !state.QueryState.HasFlag(QueryState.AllowFirstSingleOrDefault))
                {
                    throw new InvalidOperationException("Sequence contains no elements");
                }

                if (result.Batch.EntityResults.Count > 1 && state.QueryState.HasFlag(QueryState.IsSingle))
                {
                    throw new InvalidOperationException("Sequence contains more than one element");
                }

                if (result.Batch.EntityResults.Any())
                {
                    return(_serializer.DeserializeEntity(result.Batch.EntityResults[0].Entity));
                }

                return(null);
            }

            // Any() method
            if (state.QueryState.HasFlag(QueryState.IsAny))
            {
                return(result.Batch.EntityResults.Any());
            }

            // Regular Where() query
            return(result.Batch.EntityResults.Select(entityResult => _serializer.DeserializeEntity(entityResult.Entity)).ToList());
        }
示例#31
0
        internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms())
        {
            ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing);
            ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset);
            ThrowUnsupportedIfKeywordSet(KEY.Context_Connection);

            // Network Library has its own special error message
            if (ContainsKey(KEY.Network_Library))
            {
                throw SQL.NetworkLibraryKeywordNotSupported();
            }

            _integratedSecurity = ConvertValueToIntegratedSecurity();
#if netcoreapp
            _poolBlockingPeriod = ConvertValueToPoolBlockingPeriod();
#endif
            _encrypt             = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt);
            _enlist              = ConvertValueToBoolean(KEY.Enlist, DEFAULT.Enlist);
            _mars                = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS);
            _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info);
            _pooling             = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling);
            _replication         = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication);
            _userInstance        = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance);
            _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover);

            _connectTimeout       = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout);
            _loadBalanceTimeout   = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout);
            _maxPoolSize          = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size);
            _minPoolSize          = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size);
            _packetSize           = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size);
            _connectRetryCount    = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count);
            _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval);

            _applicationIntent       = ConvertValueToApplicationIntent();
            _applicationName         = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name);
            _attachDBFileName        = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename);
            _currentLanguage         = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language);
            _dataSource              = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source);
            _localDBInstance         = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
            _failoverPartner         = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner);
            _initialCatalog          = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog);
            _password                = ConvertValueToString(KEY.Password, DEFAULT.Password);
            _trustServerCertificate  = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate);
            _authType                = ConvertValueToAuthenticationType();
            _columnEncryptionSetting = ConvertValueToColumnEncryptionSetting();
            _enclaveAttestationUrl   = ConvertValueToString(KEY.EnclaveAttestationUrl, DEFAULT.EnclaveAttestationUrl);

            // Temporary string - this value is stored internally as an enum.
            string typeSystemVersionString  = ConvertValueToString(KEY.Type_System_Version, null);
            string transactionBindingString = ConvertValueToString(KEY.TransactionBinding, null);

            _userID        = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID);
            _workstationId = ConvertValueToString(KEY.Workstation_Id, null);



            if (_loadBalanceTimeout < 0)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout);
            }

            if (_connectTimeout < 0)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout);
            }

            if (_maxPoolSize < 1)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size);
            }

            if (_minPoolSize < 0)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size);
            }
            if (_maxPoolSize < _minPoolSize)
            {
                throw ADP.InvalidMinMaxPoolSizeValues();
            }

            if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize))
            {
                throw SQL.InvalidPacketSizeValue();
            }


            ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name);
            ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language);
            ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
            ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner);
            ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog);
            ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password);
            ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID);
            if (null != _workstationId)
            {
                ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id);
            }

            if (!string.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase))
            {
                // fail-over partner is set

                if (_multiSubnetFailover)
                {
                    throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null);
                }

                if (string.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase))
                {
                    throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog);
                }
            }

            if (0 <= _attachDBFileName.IndexOf('|'))
            {
                throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename);
            }
            else
            {
                ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename);
            }

            _typeSystemAssemblyVersion = constTypeSystemAsmVersion10;

            if (true == _userInstance && !string.IsNullOrEmpty(_failoverPartner))
            {
                throw SQL.UserInstanceFailoverNotCompatible();
            }

            if (string.IsNullOrEmpty(typeSystemVersionString))
            {
                typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion;
            }

            if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.Latest;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2000;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2005;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2008;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion         = TypeSystem.SQLServer2012;
                _typeSystemAssemblyVersion = constTypeSystemAsmVersion11;
            }
            else
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version);
            }

            if (string.IsNullOrEmpty(transactionBindingString))
            {
                transactionBindingString = DbConnectionStringDefaults.TransactionBinding;
            }

            if (transactionBindingString.Equals(TRANSACTIONBINDING.ImplicitUnbind, StringComparison.OrdinalIgnoreCase))
            {
                _transactionBinding = TransactionBindingEnum.ImplicitUnbind;
            }
            else if (transactionBindingString.Equals(TRANSACTIONBINDING.ExplicitUnbind, StringComparison.OrdinalIgnoreCase))
            {
                _transactionBinding = TransactionBindingEnum.ExplicitUnbind;
            }
            else
            {
                throw ADP.InvalidConnectionOptionValue(KEY.TransactionBinding);
            }

            if (_applicationIntent == ApplicationIntent.ReadOnly && !string.IsNullOrEmpty(_failoverPartner))
            {
                throw SQL.ROR_FailoverNotSupportedConnString();
            }

            if ((_connectRetryCount < 0) || (_connectRetryCount > 255))
            {
                throw ADP.InvalidConnectRetryCountValue();
            }

            if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60))
            {
                throw ADP.InvalidConnectRetryIntervalValue();
            }

            if (Authentication != SqlAuthenticationMethod.NotSpecified && _integratedSecurity == true)
            {
                throw SQL.AuthenticationAndIntegratedSecurity();
            }

            if (Authentication == SqlClient.SqlAuthenticationMethod.ActiveDirectoryIntegrated && (HasUserIdKeyword || HasPasswordKeyword))
            {
                throw SQL.IntegratedWithUserIDAndPassword();
            }

            if (Authentication == SqlAuthenticationMethod.ActiveDirectoryInteractive && !HasUserIdKeyword)
            {
                throw SQL.InteractiveWithoutUserID();
            }

            if (Authentication == SqlAuthenticationMethod.ActiveDirectoryInteractive && HasPasswordKeyword)
            {
                throw SQL.InteractiveWithPassword();
            }
        }
示例#32
0
        StructDeclarationSyntax Build()
        {
            if (IterationContext.UpdateMode == UpdateMode.OnEnd)
            {
                throw new RoslynEcsTranslator.JobSystemNotCompatibleException("Exit stacks are not compatible with jobs yet");
            }

            // Todo: disabled at the moment - job scheduling needs to use the enter query which uses an excluded component
            if (IterationContext.UpdateMode == UpdateMode.OnStart)
            {
                throw new RoslynEcsTranslator.JobSystemNotCompatibleException("Enter stacks are not compatible with jobs yet");
            }

            if (m_UpdateSingletonRequested)
            {
                throw new RoslynEcsTranslator.JobSystemNotCompatibleException("Setting a blackboard variable is not compatible with jobs yet");
            }

            var stateComponentName = IterationContext.UpdateMode == UpdateMode.OnUpdate || IterationContext.UpdateMode == UpdateMode.OnEvent
                ? null
                : IncludeTrackingSystemStateComponent(IterationContext.Query.ComponentQueryDeclarationModel, IterationContext.UpdateMode == UpdateMode.OnEnd);

            var functionParameters = new List <ParameterSyntax>
            {
                Parameter(Identifier(EntityName)).WithType(TypeSystem.BuildTypeSyntax(typeof(Entity))),
                Parameter(Identifier(GetJobIndexParameterName())).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))
            };

            var baseTypeSyntax = MakeJobBaseType(IterationContext, functionParameters, out Type eventType);

            if (baseTypeSyntax == null)
            {
                return(null);
            }
            StructDeclarationSyntax structDeclaration = StructDeclaration(m_JobName);

            if (BurstCompileJobs)
            {
                structDeclaration = structDeclaration.AddAttributeLists(
                    AttributeList().AddAttributes(
                        Attribute(IdentifierName("BurstCompile"))));
            }

            structDeclaration = DeclareExcludedComponents(structDeclaration);

            var makeJobUpdateOverride = MakeJobUpdateOverride(functionParameters, m_UpdateStatements, stateComponentName, eventType);

            structDeclaration = structDeclaration
                                .AddBaseListTypes(baseTypeSyntax)
                                .WithMembers(List(m_MemberDeclarations))
                                .AddMembers(makeJobUpdateOverride);
            return(structDeclaration);

            StructDeclarationSyntax DeclareExcludedComponents(StructDeclarationSyntax declaration)
            {
                if (m_ExcludedComponents.Count == 0)
                {
                    return(declaration);
                }

                List <AttributeArgumentSyntax> componentsToExclude = new List <AttributeArgumentSyntax>();

                foreach (var excludedComponent in m_ExcludedComponents)
                {
                    var arg = AttributeArgument(TypeOfExpression(excludedComponent.ToTypeSyntax(IterationContext.Stencil)));
                    componentsToExclude.Add(arg);
                }

                var syntaxNodes = new SyntaxNodeOrToken[componentsToExclude.Count * 2 - 1];

                syntaxNodes[0] = componentsToExclude[0];
                for (var index = 1; index < componentsToExclude.Count; index++)
                {
                    syntaxNodes[index * 2 - 1] = Token(SyntaxKind.CommaToken);
                    syntaxNodes[index * 2]     = componentsToExclude[index];
                }

                declaration = declaration.AddAttributeLists(
                    AttributeList().AddAttributes(
                        Attribute(IdentifierName("ExcludeComponent"))
                        .WithArgumentList(
                            AttributeArgumentList(SeparatedList <AttributeArgumentSyntax>(syntaxNodes)))));

                return(declaration);
            }
        }
示例#33
0
        private static IEnumerable <TypedParameter> GetBinaryFuncArgs()
        {
            yield return(new TypedParameter("x", TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var)));

            yield return(new TypedParameter("y", TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var)));
        }
示例#34
0
        // This c-tor is used to create SSE and user instance connection strings when user instance is set to true
        // 
        internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance, bool? setEnlistValue) : base(connectionOptions) {
            _integratedSecurity       = connectionOptions._integratedSecurity;
            _connectionReset          = connectionOptions._connectionReset;
            _contextConnection        = connectionOptions._contextConnection;
            _encrypt                  = connectionOptions._encrypt;

            if (setEnlistValue.HasValue) {
                _enlist = setEnlistValue.Value;
            }
            else {
                _enlist = connectionOptions._enlist;
            }
            
            _mars                     = connectionOptions._mars;
            _persistSecurityInfo      = connectionOptions._persistSecurityInfo;
            _pooling                  = connectionOptions._pooling;
            _replication              = connectionOptions._replication;
            _userInstance             = userInstance;
            _connectTimeout           = connectionOptions._connectTimeout;
            _loadBalanceTimeout       = connectionOptions._loadBalanceTimeout;
            _maxPoolSize              = connectionOptions._maxPoolSize;
            _minPoolSize              = connectionOptions._minPoolSize;
            _multiSubnetFailover      = connectionOptions._multiSubnetFailover;
            _packetSize               = connectionOptions._packetSize;
            _applicationName          = connectionOptions._applicationName;
            _attachDBFileName         = connectionOptions._attachDBFileName;
            _currentLanguage          = connectionOptions._currentLanguage;
            _dataSource               = dataSource;
            _localDBInstance          = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
            _failoverPartner          = connectionOptions._failoverPartner;
            _initialCatalog           = connectionOptions._initialCatalog;
            _password                 = connectionOptions._password;
            _userID                   = connectionOptions._userID;
            _networkLibrary           = connectionOptions._networkLibrary;
            _workstationId            = connectionOptions._workstationId;
            _expandedAttachDBFilename = connectionOptions._expandedAttachDBFilename;
            _typeSystemVersion        = connectionOptions._typeSystemVersion;
            _typeSystemAssemblyVersion =connectionOptions._typeSystemAssemblyVersion;
            _transactionBinding       = connectionOptions._transactionBinding;
            _applicationIntent        = connectionOptions._applicationIntent;
            _connectRetryCount        = connectionOptions._connectRetryCount;
            _connectRetryInterval     = connectionOptions._connectRetryInterval;
            _authType                 = connectionOptions._authType;
            _columnEncryptionSetting = connectionOptions._columnEncryptionSetting;
            ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
        }
示例#35
0
 public BinaryExpression(BinaryOperator @operator, Expression left, Expression right, TypeSystem typeSystem, IEnumerable <Instruction> instructions, bool isOverridenOperation = false)
     : this(@operator, left, right, typeSystem, DetermineIsChecked(instructions), instructions, isOverridenOperation)
 {
 }
 public ObjectInitialisationPattern(CodePatternsContext patternsContext, TypeSystem typeSystem)
     : base(patternsContext, typeSystem)
 {
 }
示例#37
0
 public OperatorStep(BaseCodeTransformer codeTransformer, TypeSystem typeSystem)
 {
     this.codeTransformer = codeTransformer;
     this.typeSystem      = typeSystem;
 }
示例#38
0
 /// <summary>
 /// Is the type or element type (in the case of nullableOfT or IEnumOfT) a structured type?
 /// </summary>
 /// <param name="type">Type to examine</param>
 /// <returns>bool indicating whether or not structured type</returns>
 internal static bool TypeOrElementTypeIsStructured(Type type)
 {
     type = TypeSystem.GetElementType(type);
     type = Nullable.GetUnderlyingType(type) ?? type;
     return(!PrimitiveType.IsKnownType(type) && !type.IsEnum());
 }
 protected MethodDefiniteAssignmentChecker(TypeSystem t, Analyzer analyzer, PreDAStatus preResult) {
   typeSystem=t;
   iVisitor=new DefiniteAssignmentInstructionVisitor(analyzer, this, preResult);
   reportedErrors=new Hashtable();
   this.analyzer = analyzer;
   this.nodeExistentialTable = new NodeMaybeExistentialDelayInfo ();
 }
示例#40
0
 /// <summary>
 /// Compiles the linker method.
 /// </summary>
 /// <param name="methodName">Name of the method.</param>
 /// <returns></returns>
 public MosaMethod CreateLinkerMethod(string methodName)
 {
     return(TypeSystem.CreateLinkerMethod(methodName, TypeSystem.BuiltIn.Void, null));
 }
示例#41
0
        internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms(), false) {

            bool   runningInProc  = InOutOfProcHelper.InProc;
            
            _integratedSecurity = ConvertValueToIntegratedSecurity();

            ConvertValueToBoolean(KEY.AsynchronousProcessing, DEFAULT.Asynchronous); // while we don't use it anymore, we still need to verify it is true/false

            // SQLPT 41700: Ignore ResetConnection=False (still validate the keyword/value)
            _connectionReset     = ConvertValueToBoolean(KEY.Connection_Reset,      DEFAULT.Connection_Reset);
            _contextConnection   = ConvertValueToBoolean(KEY.Context_Connection,    DEFAULT.Context_Connection);
            _encrypt             = ConvertValueToEncrypt();
            _enlist              = ConvertValueToBoolean(KEY.Enlist,                ADP.IsWindowsNT);
            _mars                = ConvertValueToBoolean(KEY.MARS,                  DEFAULT.MARS);
            _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info);
            _pooling             = ConvertValueToBoolean(KEY.Pooling,               DEFAULT.Pooling);
            _replication         = ConvertValueToBoolean(KEY.Replication,           DEFAULT.Replication);
            _userInstance        = ConvertValueToBoolean(KEY.User_Instance,         DEFAULT.User_Instance);
            _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover,   DEFAULT.MultiSubnetFailover);

            _connectTimeout     = ConvertValueToInt32(KEY.Connect_Timeout,       DEFAULT.Connect_Timeout);
            _loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout,  DEFAULT.Load_Balance_Timeout);
            _maxPoolSize        = ConvertValueToInt32(KEY.Max_Pool_Size,         DEFAULT.Max_Pool_Size);
            _minPoolSize        = ConvertValueToInt32(KEY.Min_Pool_Size,         DEFAULT.Min_Pool_Size);
            _packetSize         = ConvertValueToInt32(KEY.Packet_Size,           DEFAULT.Packet_Size);
            _connectRetryCount  = ConvertValueToInt32(KEY.Connect_Retry_Count,   DEFAULT.Connect_Retry_Count);
            _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval);

            _applicationIntent = ConvertValueToApplicationIntent();
            _applicationName  = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name);
            _attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename);
            _currentLanguage  = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language);
            _dataSource       = ConvertValueToString(KEY.Data_Source,      DEFAULT.Data_Source);
            _localDBInstance  = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
            _failoverPartner  = ConvertValueToString(KEY.FailoverPartner,  DEFAULT.FailoverPartner);
            _initialCatalog   = ConvertValueToString(KEY.Initial_Catalog,  DEFAULT.Initial_Catalog);
            _networkLibrary   = ConvertValueToString(KEY.Network_Library,  null);
            _password         = ConvertValueToString(KEY.Password,         DEFAULT.Password);
            _trustServerCertificate  = ConvertValueToBoolean(KEY.TrustServerCertificate,  DEFAULT.TrustServerCertificate);
            _authType = ConvertValueToAuthenticationType();
            _columnEncryptionSetting = ConvertValueToColumnEncryptionSetting();

            // Temporary string - this value is stored internally as an enum.
            string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null);
            string transactionBindingString = ConvertValueToString(KEY.TransactionBinding, null);

            _userID           = ConvertValueToString(KEY.User_ID,          DEFAULT.User_ID);
            _workstationId    = ConvertValueToString(KEY.Workstation_Id,   null);

            if (_contextConnection) {
                // We have to be running in the engine for you to request a 
                // context connection.

                if (!runningInProc) {
                    throw SQL.ContextUnavailableOutOfProc();
                }

                // When using a context connection, we need to ensure that no 
                // other connection string keywords are specified.

                foreach (DictionaryEntry entry in Parsetable) {
                    if ((string) entry.Key != KEY.Context_Connection &&
                        (string) entry.Key != KEY.Type_System_Version) {
                        throw SQL.ContextAllowsLimitedKeywords();
                    }
                }
            }

            if (!_encrypt) {    // Support legacy registry encryption settings
                const string folder = "Software\\Microsoft\\MSSQLServer\\Client\\SuperSocketNetLib";
                const string value    = "Encrypt";

                Object obj = ADP.LocalMachineRegistryValue(folder, value);
                if ((obj is Int32) && (1 == (int)obj)) {         // If the registry key exists
                    _encrypt    = true;
                }
            }


            if (_loadBalanceTimeout < 0) {
                throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout);
            }

            if (_connectTimeout < 0) {
                throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout);
            }

            if (_maxPoolSize < 1) {
                throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size);
            }

            if (_minPoolSize < 0) {
                throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size);
            }
            if (_maxPoolSize < _minPoolSize) {
                throw ADP.InvalidMinMaxPoolSizeValues();
            }

            if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize)) {
                throw SQL.InvalidPacketSizeValue();
            }

            if (null != _networkLibrary) { // MDAC 83525
                string networkLibrary = _networkLibrary.Trim().ToLower(CultureInfo.InvariantCulture);
                Hashtable netlib = NetlibMapping();
                if (!netlib.ContainsKey(networkLibrary)) {
                    throw ADP.InvalidConnectionOptionValue(KEY.Network_Library);
                }
                _networkLibrary = (string) netlib[networkLibrary];
            }
            else {
                _networkLibrary = DEFAULT.Network_Library;
            }

            ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name);
            ValidateValueLength(_currentLanguage , TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language);
            ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
            ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner);
            ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog);
            ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password);
            ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID);
            if (null != _workstationId) {
                ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id);
            }

            if (!String.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase)) {
                // fail-over partner is set

                if (_multiSubnetFailover) {
                    throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null);
                }

                if (String.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase)) {
                    throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog);
                }
            }

            // expand during construction so that CreatePermissionSet and Expand are consistent
            string datadir = null;
            _expandedAttachDBFilename = ExpandDataDirectory(KEY.AttachDBFilename, _attachDBFileName, ref datadir);
            if (null != _expandedAttachDBFilename) {
                if (0 <= _expandedAttachDBFilename.IndexOf('|')) {
                    throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename);
                }
                ValidateValueLength(_expandedAttachDBFilename, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename);
                if (_localDBInstance == null)
                {
                    // fail fast to verify LocalHost when using |DataDirectory|
                    // still must check again at connect time
                    string host = _dataSource;
                    string protocol = _networkLibrary;
                    TdsParserStaticMethods.AliasRegistryLookup(ref host, ref protocol);
                    VerifyLocalHostAndFixup(ref host, true, false /*don't fix-up*/);
                }
            }
            else if (0 <= _attachDBFileName.IndexOf('|')) {
                throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename);
            }
            else {
                ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename);
            }

            _typeSystemAssemblyVersion = constTypeSystemAsmVersion10;

            if (true == _userInstance && !ADP.IsEmpty(_failoverPartner)) {
                throw SQL.UserInstanceFailoverNotCompatible();
            }

            if (ADP.IsEmpty(typeSystemVersionString)) {
                typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion;
            }

            if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase)) {
                _typeSystemVersion = TypeSystem.Latest;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase)) {
                if (_contextConnection) {
                    throw SQL.ContextAllowsOnlyTypeSystem2005();
                }
                _typeSystemVersion = TypeSystem.SQLServer2000;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase)) {
                _typeSystemVersion = TypeSystem.SQLServer2005;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase)) {
                _typeSystemVersion = TypeSystem.SQLServer2008;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase)) {
                _typeSystemVersion = TypeSystem.SQLServer2012;
                _typeSystemAssemblyVersion = constTypeSystemAsmVersion11;
            }
            else {
                throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version);
            }

            if (ADP.IsEmpty(transactionBindingString)) {
                transactionBindingString = DbConnectionStringDefaults.TransactionBinding;
            }

            if (transactionBindingString.Equals(TRANSACIONBINDING.ImplicitUnbind, StringComparison.OrdinalIgnoreCase)) {
                _transactionBinding = TransactionBindingEnum.ImplicitUnbind;
            }
            else if (transactionBindingString.Equals(TRANSACIONBINDING.ExplicitUnbind, StringComparison.OrdinalIgnoreCase)) {
                _transactionBinding = TransactionBindingEnum.ExplicitUnbind;
            }
            else {
                throw ADP.InvalidConnectionOptionValue(KEY.TransactionBinding);
            }

            if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner))
                throw SQL.ROR_FailoverNotSupportedConnString();

            if ((_connectRetryCount<0) || (_connectRetryCount>255)) {
                throw ADP.InvalidConnectRetryCountValue();
            }

            if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60)) {
                throw ADP.InvalidConnectRetryIntervalValue();
            }

            if (Authentication != SqlAuthenticationMethod.NotSpecified && _integratedSecurity == true) {
                throw SQL.AuthenticationAndIntegratedSecurity();
            }

            if (Authentication == SqlClient.SqlAuthenticationMethod.ActiveDirectoryIntegrated && (HasUserIdKeyword || HasPasswordKeyword)) {
                throw SQL.IntegratedWithUserIDAndPassword();
            }
        }
 internal SingleKeyManager(MetaAccessor <T, V> accessor, int offset)
 {
     this.accessor            = accessor;
     this.offset              = offset;
     this.isKeyNullAssignable = TypeSystem.IsNullAssignable(typeof(V));
 }
示例#43
0
 public Resolver(ErrorHandler errorHandler, TypeSystem typeSystem)
   : base(errorHandler){
   Debug.Assert(typeSystem != null);
   this.typeSystem = typeSystem;
   this.useGenerics = TargetPlatform.UseGenerics;
 }
 public static Literal TryEvalBinaryExpression(Literal opnd1, Literal opnd2, BinaryExpression binaryExpression, TypeSystem typeSystem){
   try{
     return PureEvaluator.EvalBinaryExpression(opnd1, opnd2, binaryExpression, typeSystem);
   }
   catch{
     return null;
   }
 }
示例#45
0
        BaseTypeSyntax MakeJobBaseType(RoslynEcsTranslator.IterationContext iterationContext, List <ParameterSyntax> functionParameters, out Type eventType)
        {
            var genericArguments = new List <TypeSyntax>();

            eventType = null;
            int componentCount = 0;
            int bufferCount    = 0;

            if (iterationContext.UpdateMode != UpdateMode.OnEnd)
            {
                if (iterationContext.UpdateMode == UpdateMode.OnEvent) // add DynamicBuffer<eventType>
                {
                    eventType = ((OnEventNodeModel)iterationContext.Query).EventTypeHandle.Resolve(iterationContext.Stencil);
                    var eventTypeSyntax = TypeSystem.BuildTypeSyntax(eventType);
                    var bufferType      = GenericName("DynamicBuffer")
                                          .WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(eventTypeSyntax)));
                    var parameterSyntax = Parameter(
                        Identifier(OnEventNodeModel.GetBufferName(eventType)))
                                          .WithType(bufferType);
                    AddReadOnlyAttribute(ref parameterSyntax);

                    bufferCount = 1;

                    functionParameters.Add(parameterSyntax);
                    genericArguments.Add(eventTypeSyntax);
                }


                foreach (ComponentDefinition definition in iterationContext.FlattenedComponentDefinitions().Where(def => !def.Subtract))
                {
                    if (!RoslynEcsTranslatorExtensions.ShouldGenerateComponentAccess(definition.TypeHandle, true, out Type resolvedType, iterationContext.Stencil, out bool isShared, out bool isGameObjectComponent) ||
                        isGameObjectComponent)
                    {
                        continue;
                    }

                    if (isShared)
                    {
                        throw new RoslynEcsTranslator.JobSystemNotCompatibleException("Shared Components are not supported in jobs yet");
                    }

                    genericArguments.Add(TypeSystem.BuildTypeSyntax(resolvedType));
                    var parameterSyntax = Parameter(
                        Identifier(GetComponentVariableName(iterationContext.Query, definition.TypeHandle)))
                                          .WithModifiers(TokenList(Token(SyntaxKind.RefKeyword)))
                                          .WithType(TypeSystem.BuildTypeSyntax(resolvedType));
                    if (!m_WrittenComponents.Contains(definition.TypeHandle))
                    {
                        AddReadOnlyAttribute(ref parameterSyntax);
                    }
                    functionParameters.Add(
                        parameterSyntax);
                    componentCount++;
                }

                if (genericArguments.Count == 0)
                {
                    return(null);
                }
            }

            string CleanGenericName(string s)
            {
                var index = s.IndexOf('`');

                return(index == -1 ? s : s.Substring(0, index));
            }

            // IJobForEachWitEntity_EBBCCC
            string suffix = componentCount > 0 || bufferCount > 0
                ? $"_E{new String('B', bufferCount)}{new String('C', componentCount)}"
                : "";

            return(SimpleBaseType(
                       GenericName(
                           Identifier(CleanGenericName(typeof(IJobForEachWithEntity <>).Name) + suffix))
                       .WithTypeArgumentList(
                           TypeArgumentList(
                               SeparatedList(
                                   genericArguments)))));

            ParameterSyntax AddReadOnlyAttribute(ref ParameterSyntax parameterSyntax)
            {
                return(parameterSyntax = parameterSyntax.WithAttributeLists(
                           SingletonList(
                               AttributeList(
                                   SingletonSeparatedList(
                                       Attribute(
                                           IdentifierName(nameof(ReadOnlyAttribute))))))));
            }
        }
        public static bool MethodSignatureHasVarsNeedingCallingConventionConverter_MethodSignature(TypeSystem.MethodSignature methodSignature)
        {
            if (TypeHasLayoutDependentOnGenericInstantiation(methodSignature.ReturnType, HasVarsInvestigationLevel.Parameter))
                return true;

            for (int i = 0; i < methodSignature.Length; i++)
            {
                if (TypeHasLayoutDependentOnGenericInstantiation(methodSignature[i], HasVarsInvestigationLevel.Parameter))
                    return true;
            }

            return false;
        }
 /// <summary>
 /// Tries to return the literal obtained from constant folding the binary expression whose literal arguments are given
 /// by opnd1 and opnd2. If any of these are null, the result is null. If the binary expression cannot be constant folded
 /// the result is also null.
 /// </summary>
 /// <param name="opnd1">null or literal corresponding to binary expression's 1st constant folded argument</param>
 /// <param name="opnd2">null or literal corresponding to binary expression's 2nd constant folded argument</param>
 /// <param name="binaryExpression">the original binary expression</param>
 /// <returns>null, or constant folded literal</returns>
 public static Literal EvalBinaryExpression(Literal opnd1, Literal opnd2, BinaryExpression binaryExpression, TypeSystem typeSystem){
   if (binaryExpression == null) return null;
   if (opnd1 == null) return null;
   if (opnd2 == null) return null;
   IConvertible ic1 = opnd1.Value as IConvertible;
   IConvertible ic2 = opnd2.Value as IConvertible;
   TypeCode code1 = ic1 == null ? TypeCode.Object : ic1.GetTypeCode();
   TypeCode code2 = ic2 == null ? TypeCode.Object : ic2.GetTypeCode();
   TypeNode type = SystemTypes.Object;
   object val = null;
   switch (binaryExpression.NodeType){
     case NodeType.Add :
       if (typeSystem != null && typeSystem.checkOverflow) goto case NodeType.Add_Ovf;
       return PureEvaluator.DoAdd(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Add_Ovf : 
     case NodeType.Add_Ovf_Un : 
       return PureEvaluator.DoAddOvf(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.AddEventHandler :
       return null;
     case NodeType.And : 
       return PureEvaluator.DoAnd(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.As :
       return null;
     case NodeType.Box :
     case NodeType.Castclass : 
     case NodeType.ExplicitCoercion :
       type = (TypeNode)opnd2.Value;
       TypeNode t = type;
       EnumNode en = type as EnumNode;
       if (en != null) t = en.UnderlyingType;
       if (t == null || !t.IsPrimitive) return null;
       if (typeSystem != null && binaryExpression.NodeType == NodeType.ExplicitCoercion){
         ErrorHandler savedErrorHandler = typeSystem.ErrorHandler;
         typeSystem.ErrorHandler = null;
         Expression result;
         try {
           result = typeSystem.ExplicitLiteralCoercion(opnd1, opnd1.Type, t, null);
         }
         finally {
           typeSystem.ErrorHandler = savedErrorHandler;
         };
         return result as Literal;
       }
       Type rt = t.GetRuntimeType();
       if (rt != null)
         val = Convert.ChangeType(opnd1.Value, rt, null);
       else
         val = opnd1.Value;
       break;
     case NodeType.Ceq : 
     case NodeType.Cgt : 
     case NodeType.Cgt_Un : 
     case NodeType.Clt : 
     case NodeType.Clt_Un : 
       return null;
     case NodeType.Comma:
       return opnd2;
     case NodeType.Div : 
     case NodeType.Div_Un : 
       return PureEvaluator.DoDiv(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Eq : 
       return PureEvaluator.DoEq(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Ge : 
       return PureEvaluator.DoGe(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Gt : 
       return PureEvaluator.DoGt(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Is : 
     case NodeType.Isinst : 
     case NodeType.Ldvirtftn :
       return null;
     case NodeType.Le : 
       return PureEvaluator.DoLe(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.LogicalAnd :
       return PureEvaluator.DoLogicalAnd(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.LogicalOr :
       return PureEvaluator.DoLogicalOr(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Lt : 
       return PureEvaluator.DoLt(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Mkrefany :
       return null;
     case NodeType.Mul :
       if (typeSystem != null && typeSystem.checkOverflow) goto case NodeType.Mul_Ovf;
       return PureEvaluator.DoMul(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Mul_Ovf : 
     case NodeType.Mul_Ovf_Un : 
       return PureEvaluator.DoMulOvf(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Ne : 
       return PureEvaluator.DoNe(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Or : 
       return PureEvaluator.DoOr(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Refanyval :
       return null;
     case NodeType.Rem : 
     case NodeType.Rem_Un : 
       return PureEvaluator.DoRem(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.RemoveEventHandler :
       return null;
     case NodeType.Shl : 
       return PureEvaluator.DoLeftShift(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Shr : 
     case NodeType.Shr_Un : 
       return PureEvaluator.DoRightShift(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Sub :
       if (typeSystem != null && typeSystem.checkOverflow) goto case NodeType.Sub_Ovf;
       return PureEvaluator.DoSub(ic1, ic2, code1, code2, binaryExpression);        
     case NodeType.Sub_Ovf : 
     case NodeType.Sub_Ovf_Un : 
       return PureEvaluator.DoSubOvf(ic1, ic2, code1, code2, binaryExpression);
     case NodeType.Unbox : 
     case NodeType.Xor :
     default:
       return null;
   }
   return new Literal(val, type, binaryExpression.SourceContext);
 }
示例#48
0
        public static void UpdateTree(TreeView treeView, TypeSystem typeSystem, MosaTypeLayout typeLayout, bool showSizes)
        {
            treeView.BeginUpdate();
            treeView.Nodes.Clear();

            foreach (var module in typeSystem.Modules)
            {
                var namespaces = new List <TreeNode>();

                var moduleNode = new TreeNode(module.Name);
                treeView.Nodes.Add(moduleNode);

                var typeList = (new List <MosaType>(module.Types.Values)).OrderBy(o => o.FullName).ToList();

                foreach (var type in typeList)
                {
                    TreeNode namespaceNode = null;
                    string   @namespace    = (string.IsNullOrWhiteSpace(type.Namespace)) ? "[No Namespace]" : type.Namespace;
                    foreach (var node in namespaces)
                    {
                        if (node.Text.Equals(@namespace))
                        {
                            namespaceNode = node;
                            break;
                        }
                    }

                    if (namespaceNode == null)
                    {
                        namespaceNode = new TreeNode(@namespace);
                        moduleNode.Nodes.Add(namespaceNode);
                        namespaces.Add(namespaceNode);
                    }

                    var typeNode = new TreeNode(type.FullName);
                    namespaceNode.Nodes.Add(typeNode);

                    if (type.BaseType != null)
                    {
                        var baseTypeNode = new TreeNode("Base Type: " + type.BaseType.FullName);
                        typeNode.Nodes.Add(baseTypeNode);
                    }

                    if (type.DeclaringType != null)
                    {
                        var declaringTypeNode = new TreeNode("Declaring Type: " + type.DeclaringType.FullName);
                        typeNode.Nodes.Add(declaringTypeNode);
                    }

                    if (type.ElementType != null)
                    {
                        var elementTypeNode = new TreeNode("Element Type: " + type.ElementType.FullName);
                        typeNode.Nodes.Add(elementTypeNode);
                    }

                    if (type.Interfaces.Count != 0)
                    {
                        var interfacesNodes = new TreeNode("Interfaces");
                        typeNode.Nodes.Add(interfacesNodes);

                        foreach (var interfaceType in type.Interfaces)
                        {
                            var interfaceNode = new TreeNode(interfaceType.FullName);
                            interfacesNodes.Nodes.Add(interfaceNode);
                        }
                    }

                    if (type.Fields.Count != 0)
                    {
                        var fieldsNode = new TreeNode("Fields");
                        if (showSizes)
                        {
                            fieldsNode.Text = fieldsNode.Text + " (Count: " + type.Fields.Count.ToString() + " - Size: " + typeLayout.GetTypeSize(type).ToString() + ")";
                        }

                        typeNode.Nodes.Add(fieldsNode);

                        foreach (var field in type.Fields)
                        {
                            var fieldNode = new TreeNode(field.ShortName);
                            fieldsNode.Nodes.Add(fieldNode);

                            if (field.IsStatic)
                            {
                                fieldNode.Text = fieldNode.Text + " [Static]";
                            }

                            if (showSizes)
                            {
                                fieldNode.Text = fieldNode.Text + " (Size: " + typeLayout.GetFieldSize(field).ToString();

                                if (!field.IsStatic)
                                {
                                    fieldNode.Text = fieldNode.Text + " - Offset: " + typeLayout.GetFieldOffset(field).ToString();
                                }

                                fieldNode.Text = fieldNode.Text + ")";
                            }
                        }
                    }

                    if (type.Properties.Count != 0)
                    {
                        var propertiesNode = new TreeNode("Properties");
                        if (showSizes)
                        {
                            propertiesNode.Text = propertiesNode.Text + " (Count: " + type.Properties.Count.ToString() + ")";
                        }

                        typeNode.Nodes.Add(propertiesNode);

                        foreach (var property in type.Properties)
                        {
                            var propertyNode = new ViewNode <MosaProperty>(property, property.ShortName);
                            propertiesNode.Nodes.Add(propertyNode);

                            if (property.GetterMethod != null)
                            {
                                var getterNode = new ViewNode <MosaMethod>(property.GetterMethod, property.GetterMethod.ShortName);
                                propertyNode.Nodes.Add(getterNode);

                                if (property.GetterMethod.IsStatic)
                                {
                                    getterNode.Text = getterNode.Text + " [Static]";
                                }

                                if (property.GetterMethod.IsAbstract)
                                {
                                    getterNode.Text = getterNode.Text + " [Abstract]";
                                }

                                if (property.GetterMethod.IsNewSlot)
                                {
                                    getterNode.Text = getterNode.Text + " [NewSlot]";
                                }

                                if (property.GetterMethod.IsVirtual)
                                {
                                    getterNode.Text = getterNode.Text + " [Virtual]";
                                }

                                if (property.GetterMethod.IsFinal)
                                {
                                    getterNode.Text = getterNode.Text + " [Final]";
                                }

                                if (property.GetterMethod.IsSpecialName)
                                {
                                    getterNode.Text = getterNode.Text + " [SpecialName]";
                                }

                                if (property.GetterMethod.IsRTSpecialName)
                                {
                                    getterNode.Text = getterNode.Text + " [RTSpecialName]";
                                }

                                if (property.GetterMethod.GenericArguments.Count != 0)
                                {
                                    var genericParameterNodes = new TreeNode("Generic Arguments Types");
                                    getterNode.Nodes.Add(genericParameterNodes);

                                    foreach (var genericParameter in property.GetterMethod.GenericArguments)
                                    {
                                        TreeNode GenericParameterNode = new TreeNode(genericParameter.Name);
                                        genericParameterNodes.Nodes.Add(GenericParameterNode);
                                    }
                                }
                            }

                            if (property.SetterMethod != null)
                            {
                                var setterNode = new ViewNode <MosaMethod>(property.SetterMethod, property.SetterMethod.ShortName);
                                propertyNode.Nodes.Add(setterNode);

                                if (property.SetterMethod.IsStatic)
                                {
                                    setterNode.Text = setterNode.Text + " [Static]";
                                }

                                if (property.SetterMethod.IsAbstract)
                                {
                                    setterNode.Text = setterNode.Text + " [Abstract]";
                                }

                                if (property.SetterMethod.IsNewSlot)
                                {
                                    setterNode.Text = setterNode.Text + " [NewSlot]";
                                }

                                if (property.SetterMethod.IsVirtual)
                                {
                                    setterNode.Text = setterNode.Text + " [Virtual]";
                                }

                                if (property.SetterMethod.IsFinal)
                                {
                                    setterNode.Text = setterNode.Text + " [Final]";
                                }

                                if (property.SetterMethod.IsSpecialName)
                                {
                                    setterNode.Text = setterNode.Text + " [SpecialName]";
                                }

                                if (property.SetterMethod.IsRTSpecialName)
                                {
                                    setterNode.Text = setterNode.Text + " [RTSpecialName]";
                                }

                                if (property.SetterMethod.GenericArguments.Count != 0)
                                {
                                    var genericParameterNodes = new TreeNode("Generic Arguments Types");
                                    setterNode.Nodes.Add(genericParameterNodes);

                                    foreach (var genericParameter in property.SetterMethod.GenericArguments)
                                    {
                                        var GenericParameterNode = new TreeNode(genericParameter.Name);
                                        genericParameterNodes.Nodes.Add(GenericParameterNode);
                                    }
                                }
                            }
                        }
                    }

                    if (type.Methods.Count != 0)
                    {
                        var methodsNode = new TreeNode("Methods");
                        typeNode.Nodes.Add(methodsNode);

                        foreach (MosaMethod method in type.Methods)
                        {
                            if (method.ShortName.StartsWith("set_") || method.ShortName.StartsWith("get_"))
                            {
                                continue;
                            }

                            var methodNode = new ViewNode <MosaMethod>(method, method.ShortName);
                            methodsNode.Nodes.Add(methodNode);

                            if (method.IsStatic)
                            {
                                methodNode.Text = methodNode.Text + " [Static]";
                            }

                            if (method.IsAbstract)
                            {
                                methodNode.Text = methodNode.Text + " [Abstract]";
                            }

                            if (method.IsNewSlot)
                            {
                                methodNode.Text = methodNode.Text + " [NewSlot]";
                            }

                            if (method.IsVirtual)
                            {
                                methodNode.Text = methodNode.Text + " [Virtual]";
                            }

                            if (method.IsFinal)
                            {
                                methodNode.Text = methodNode.Text + " [Final]";
                            }

                            if (method.IsSpecialName)
                            {
                                methodNode.Text = methodNode.Text + " [SpecialName]";
                            }

                            if (method.IsRTSpecialName)
                            {
                                methodNode.Text = methodNode.Text + " [RTSpecialName]";
                            }

                            if (method.GenericArguments.Count != 0)
                            {
                                var genericParameterNodes = new TreeNode("Generic Arguments Types");
                                methodNode.Nodes.Add(genericParameterNodes);

                                foreach (var genericParameter in method.GenericArguments)
                                {
                                    var GenericParameterNode = new TreeNode(genericParameter.Name);
                                    genericParameterNodes.Nodes.Add(GenericParameterNode);
                                }
                            }
                        }
                    }

                    if (typeLayout.GetMethodTable(type) != null)
                    {
                        var methodTableNode = new TreeNode("Method Table");
                        typeNode.Nodes.Add(methodTableNode);

                        foreach (var method in typeLayout.GetMethodTable(type))
                        {
                            var methodNode = new ViewNode <MosaMethod>(method, method.ShortName);
                            methodTableNode.Nodes.Add(methodNode);
                        }
                    }
                }
            }

            treeView.EndUpdate();
        }
        private static bool GetCallingConverterDataFromMethodSignature_MethodSignature(TypeSystem.MethodSignature methodSignature, NativeLayoutInfoLoadContext nativeLayoutContext, out bool hasThis, out TypeDesc[] parameters, out bool[] parametersWithGenericDependentLayout)
        {
            // Compute parameters dependent on generic instantiation for their layout
            parametersWithGenericDependentLayout = new bool[methodSignature.Length + 1];
            parametersWithGenericDependentLayout[0] = TypeHasLayoutDependentOnGenericInstantiation(methodSignature.ReturnType, HasVarsInvestigationLevel.Parameter);
            for (int i = 0; i < methodSignature.Length; i++)
            {
                parametersWithGenericDependentLayout[i + 1] = TypeHasLayoutDependentOnGenericInstantiation(methodSignature[i], HasVarsInvestigationLevel.Parameter);
            }

            // Compute hasThis-ness
            hasThis = !methodSignature.IsStatic;

            // Compute parameter exact types
            parameters = new TypeDesc[methodSignature.Length + 1];

            Instantiation typeInstantiation = nativeLayoutContext._typeArgumentHandles;
            Instantiation methodInstantiation = nativeLayoutContext._methodArgumentHandles;

            parameters[0] = methodSignature.ReturnType.InstantiateSignature(typeInstantiation, methodInstantiation);
            for (int i = 0; i < methodSignature.Length; i++)
            {
                parameters[i + 1] = methodSignature[i].InstantiateSignature(typeInstantiation, methodInstantiation);
            }

            return true;
        }
示例#50
0
        public static List <NodeModel> SpawnAllNodeModelsInGraph(VSGraphModel graphModel)
        {
            List <NodeModel>          spawnedNodes = new List <NodeModel>();
            Stencil                   stencil      = graphModel.Stencil;
            StackModel                stack;
            FunctionModel             funcModel;
            OnUpdateEntitiesNodeModel onUpdateModel;

            //--Floating Nodes--

            //Stack-Derived NodeModels
            spawnedNodes.Add(stack         = graphModel.CreateNode <StackModel>("StackModel"));
            spawnedNodes.Add(funcModel     = graphModel.CreateNode <FunctionModel>("FunctionModel"));
            spawnedNodes.Add(onUpdateModel = graphModel.CreateNode <OnUpdateEntitiesNodeModel>("OnUpdateEntitiesNodeModel"));

            var methodInfo = TypeSystem.GetMethod(typeof(Debug), nameof(Debug.Log), true);

            spawnedNodes.Add(graphModel.CreateEventFunction(methodInfo, Vector2.zero));
            spawnedNodes.Add(graphModel.CreateNode <OnEndEntitiesNodeModel>("OnEndEntitiesNodeModel"));
            spawnedNodes.Add(graphModel.CreateNode <OnEventNodeModel>("OnEventNodeModel"));
            spawnedNodes.Add(graphModel.CreateNode <OnStartEntitiesNodeModel>("OnStartEntitiesNodeModel"));
            spawnedNodes.Add(graphModel.CreateNode <PostUpdate>("PostUpdate"));
            spawnedNodes.Add(graphModel.CreateNode <PreUpdate>("PreUpdate"));
            spawnedNodes.Add(graphModel.CreateNode <KeyDownEventModel>("KeyDownEventModel"));
            spawnedNodes.Add(graphModel.CreateNode <CountEntitiesNodeModel>("CountEntitiesNodeModel"));
            spawnedNodes.Add(graphModel.CreateLoopStack(typeof(ForEachHeaderModel), Vector2.zero));
            spawnedNodes.Add(graphModel.CreateLoopStack(typeof(WhileHeaderModel), Vector2.zero));
            spawnedNodes.Add(graphModel.CreateLoopStack(typeof(ForAllEntitiesStackModel), Vector2.zero));
            spawnedNodes.Add(graphModel.CreateLoopStack(typeof(CoroutineStackModel), Vector2.zero));

            //Constant-typed NodeModels
            spawnedNodes.Add(graphModel.CreateNode <BooleanConstantNodeModel>("BooleanConstantNodeModel"));
            spawnedNodes.Add(graphModel.CreateNode <ColorConstantModel>("ColorConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <CurveConstantNodeModel>("CurveConstantNodeModel"));
            spawnedNodes.Add(graphModel.CreateNode <DoubleConstantModel>("DoubleConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <EnumConstantNodeModel>("EnumConstantNodeModel"));
            spawnedNodes.Add(graphModel.CreateNode <FloatConstantModel>("FloatConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <GetPropertyGroupNodeModel>("GetPropertyGroupNodeModel"));
            spawnedNodes.Add(graphModel.CreateNode <InputConstantModel>("InputConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <IntConstantModel>("IntConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <LayerConstantModel>("LayerConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <LayerMaskConstantModel>("LayerMaskConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <ObjectConstantModel>("ObjectConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <QuaternionConstantModel>("QuaternionConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <StringConstantModel>("StringConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <TagConstantModel>("TagConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <Vector2ConstantModel>("Vector2ConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <Vector3ConstantModel>("Vector3ConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <Vector4ConstantModel>("Vector4ConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <ConstantSceneAssetNodeModel>("ConstantSceneAssetNodeModel"));
            spawnedNodes.Add(graphModel.CreateNode <Float2ConstantModel>("Float2ConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <Float3ConstantModel>("Float3ConstantModel"));
            spawnedNodes.Add(graphModel.CreateNode <Float4ConstantModel>("Float4ConstantModel"));

            //Misc
            void DefineSystemConstant(SystemConstantNodeModel m)
            {
                m.ReturnType    = typeof(float).GenerateTypeHandle(stencil);
                m.DeclaringType = typeof(Mathf).GenerateTypeHandle(stencil);
                m.Identifier    = "PI";
            }

            spawnedNodes.Add(graphModel.CreateNode <SystemConstantNodeModel>("SystemConstantNodeModel", Vector2.zero, SpawnFlags.Default, DefineSystemConstant));
            spawnedNodes.Add(graphModel.CreateNode <GetInputNodeModel>("GetInputNodeModel"));
            spawnedNodes.Add(graphModel.CreateNode <GetOrCreateComponentNodeModel>("GetOrCreateComponentNodeModel"));
            spawnedNodes.Add(graphModel.CreateNode <GetSingletonNodeModel>("GetSingletonNodeModel"));
            spawnedNodes.Add(graphModel.CreateNode <ThisNodeModel>("ThisNodeModel"));
            VariableDeclarationModel decl = graphModel.CreateGraphVariableDeclaration("MyVariableName", typeof(int).GenerateTypeHandle(graphModel.Stencil), true);

            spawnedNodes.Add((NodeModel)graphModel.CreateVariableNode(decl, Vector2.zero));
            spawnedNodes.Add(graphModel.CreateNode <MacroRefNodeModel>("MacroRefNodeModel"));
            spawnedNodes.Add(graphModel.CreateInlineExpressionNode("2+2", Vector2.zero));
            spawnedNodes.Add(graphModel.CreateBinaryOperatorNode(BinaryOperatorKind.Add, Vector2.zero));
            spawnedNodes.Add(graphModel.CreateUnaryOperatorNode(UnaryOperatorKind.PostIncrement, Vector2.zero));

            //--Stack-Contained Nodes--
            spawnedNodes.Add(stack.CreateStackedNode <AddComponentNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <DestroyEntityNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <ForAllEntitiesNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <ForEachNodeModel>());
            spawnedNodes.Add(stack.CreateFunctionCallNode(TypeSystem.GetMethod(typeof(Debug), nameof(Debug.Log), true)));
            spawnedNodes.Add(stack.CreateFunctionRefCallNode(funcModel));
            spawnedNodes.Add(stack.CreateStackedNode <InstantiateNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <CreateEntityNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <IfConditionNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <LogNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <RemoveComponentNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <SetComponentNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <SetPositionNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <SetRotationNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <WhileNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <SetPropertyGroupNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <SetVariableNodeModel>());
            spawnedNodes.Add(stack.CreateStackedNode <CoroutineNodeModel>());
            spawnedNodes.Add(funcModel.CreateStackedNode <ReturnNodeModel>());

            TypeHandle eventTypeHandle = typeof(DummyEvent).GenerateTypeHandle(stencil);

            spawnedNodes.Add(onUpdateModel.CreateStackedNode <SendEventNodeModel>("SendEventNodeModel", 0, SpawnFlags.Default, n => n.EventType = eventTypeHandle));

            return(spawnedNodes);
        }
    /// <summary>
    /// Entry point of the check. 
    /// 
    /// It create a new instance of the checker, and run the checker on the given method.
    /// </summary>
    /// <param name="t"></param>
    /// <param name="method"></param>
    public static IDelayInfo  Check(TypeSystem t, Method method, Analyzer analyzer, PreDAStatus preResult) {
      Debug.Assert(method!=null && analyzer != null);
      MethodDefiniteAssignmentChecker checker= new MethodDefiniteAssignmentChecker(t, analyzer, preResult);
      checker.currentMethod=method;
      ControlFlowGraph cfg=analyzer.GetCFG(method);

      if(cfg==null)
        return null;

      InitializedVariables iv = new InitializedVariables(analyzer);
      checker.Run(cfg,iv);
      if (checker.exitState == null) {
        // Method has no normal return. We should consider having such method as annotated with [NoReturn].
        return checker.NodeExistentialTable;
      }
      InitializedVariables onExit = new InitializedVariables((InitializedVariables)checker.exitState);

      // check for unassigned Out parameters.
      ParameterList pl=checker.currentMethod.Parameters;
      if(pl!=null){
        for(int i=0; i < pl.Count; i++){
          Parameter p = pl[i];
          if(p.Type is Reference && p.IsOut && !onExit.IsAssignedRef(p, ((Reference)p.Type).ElementType as Struct))
            checker.typeSystem.HandleError(method.Name,Error.ParamUnassigned,p.Name.Name);
        }
      }
      // check for struct fields in constructor
      if (method is InstanceInitializer && method.DeclaringType != null && method.DeclaringType.IsValueType) {
        Field unassignedfield = onExit.NonAssignedRefField(method.ThisParameter, (Struct)method.DeclaringType);
        if (unassignedfield != null) {
          checker.typeSystem.HandleError(method, Error.UnassignedThis, checker.typeSystem.GetTypeName(unassignedfield.DeclaringType)+"."+unassignedfield.Name.Name);
        }
      }
      // if delayed constructor, check for field initializations here
      if (method is InstanceInitializer && checker.iVisitor.IsUniversallyDelayed(method.ThisParameter)) {
        checker.iVisitor.CheckCtorNonNullFieldInitialization(method.ThisParameter, method.Name, onExit, Error.NonNullFieldNotInitializedAtEndOfDelayedConstructor);
      }

      // Check for uninitialized base class
      if (method is InstanceInitializer
        && method.DeclaringType is Class
        && method.DeclaringType.BaseType != null
        && method.DeclaringType.BaseType != SystemTypes.MulticastDelegate
        && !onExit.IsBaseAssigned())
        checker.typeSystem.HandleError(method, Error.BaseNotInitialized);

      // Check for assigned but unreferenced variables.
      //TODO: this check should be moved to Looker so that constant folding does not affect it
      onExit.EmitAssignedButNotReferencedErrors(checker.typeSystem);

      return (checker.NodeExistentialTable);
    }
示例#52
0
 public BaseInitialisationPattern(CodePatternsContext patternsContext, TypeSystem ts)
 {
     base(patternsContext, ts);
     return;
 }
 private MethodReachingDefNNArrayChecker(TypeSystem ts, Analyzer analyzer, Method method) {
   TypeSystem = ts;
   this.analyzer = analyzer;
   currentMethod = method;
   iVisitor = new ReachingDefNNArrayInstructionVisitor(analyzer, this);
   okTable = new Hashtable();
   nonDelayArrayTable = new Hashtable();
   NNArrayStatus.OKAtCommit = okTable;
   NNArrayStatus.NonDelayByCreation = nonDelayArrayTable;
 }
 public SimpleVariableInliner(TypeSystem typeSystem)
 {
     this.typeSystem = typeSystem;
 }
 public void EmitAssignedButNotReferencedErrors(TypeSystem ts) {
   IWorkList wl = this.Variables;
   while ( !wl.IsEmpty()) {
     Variable v = (Variable)wl.Pull();
     if (v is Local && v.Name != StandardIds.NewObj && ((RStatus)this.referenceStatus[v]) == RStatus.Assigned) {
       ts.HandleError(v,Error.UnreferencedVarAssg,v.Name.Name);
     }
   }
 }
示例#56
0
 public MessagePackWriterHelper(ModuleDefinition module, IMetadataScope messagePackScope, Func <SystemReadOnlySpanHelper> readOnlySpanHelperFunc)
 {
     this.readOnlySpanHelperFunc = readOnlySpanHelperFunc;
     typeSystem = module.TypeSystem;
     Writer     = new TypeReference("MessagePack", "MessagePackWriter", module, messagePackScope, true);
 }
示例#57
0
 public Resolver(ErrorHandler errorHandler, TypeSystem typeSystem)
     : base(errorHandler, typeSystem)
 {
 }
示例#58
0
        private string TransformToEqualValue(WhereParams whereParams)
        {
            if (whereParams.Value == null)
            {
                return(Constants.NullValueNotAnalyzed);
            }

            if (Equals(whereParams.Value, string.Empty))
            {
                return(Constants.EmptyStringNotAnalyzed);
            }

            var type = TypeSystem.GetNonNullableType(whereParams.Value.GetType());

            if (type == typeof(bool))
            {
                return((bool)whereParams.Value ? "true" : "false");
            }

            if (type == typeof(DateTime))
            {
                var val = (DateTime)whereParams.Value;
                var s   = val.GetDefaultRavenFormat();
                if (val.Kind == DateTimeKind.Utc)
                {
                    s += "Z";
                }
                return(s);
            }

            if (type == typeof(DateTimeOffset))
            {
                var val = (DateTimeOffset)whereParams.Value;
                return(val.UtcDateTime.GetDefaultRavenFormat(true));
            }

            if (type == typeof(decimal))
            {
                return(RavenQuery.Escape(((double)((decimal)whereParams.Value)).ToString(CultureInfo.InvariantCulture), false, false));
            }

            if (type == typeof(double))
            {
                return(RavenQuery.Escape(((double)(whereParams.Value)).ToString("r", CultureInfo.InvariantCulture), false, false));
            }

            var strValue = whereParams.Value as string;

            if (strValue != null)
            {
                strValue = RavenQuery.Escape(strValue,
                                             whereParams.AllowWildcards && whereParams.IsAnalyzed, true);

                return(whereParams.IsAnalyzed ? strValue : String.Concat("[[", strValue, "]]"));
            }

            if (whereParams.Value is ValueType)
            {
                var escaped = RavenQuery.Escape(Convert.ToString(whereParams.Value, CultureInfo.InvariantCulture),
                                                whereParams.AllowWildcards && whereParams.IsAnalyzed, true);

                return(escaped);
            }

            var value = whereParams.Value as RavenJToken;

            if (value != null)
            {
                var term = value.ToString(Formatting.None).Trim('"');

                switch (value.Type)
                {
                case JTokenType.Object:
                case JTokenType.Array:
                    return("[[" + RavenQuery.Escape(term, false, false) + "]]");

                default:
                    return(RavenQuery.Escape(term, false, false));
                }
            }

            throw new NotSupportedException();
        }
示例#59
0
        // This c-tor is used to create SSE and user instance connection strings when user instance is set to true
        // BUG (VSTFDevDiv) 479687: Using TransactionScope with Linq2SQL against user instances fails with "connection has been broken" message
        internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance) : base(connectionOptions)
        {
            _integratedSecurity = connectionOptions._integratedSecurity;
            _encrypt = connectionOptions._encrypt;

            _mars = connectionOptions._mars;
            _persistSecurityInfo = connectionOptions._persistSecurityInfo;
            _pooling = connectionOptions._pooling;
            _replication = connectionOptions._replication;
            _userInstance = userInstance;
            _connectTimeout = connectionOptions._connectTimeout;
            _loadBalanceTimeout = connectionOptions._loadBalanceTimeout;
            _maxPoolSize = connectionOptions._maxPoolSize;
            _minPoolSize = connectionOptions._minPoolSize;
            _multiSubnetFailover = connectionOptions._multiSubnetFailover;
            _packetSize = connectionOptions._packetSize;
            _applicationName = connectionOptions._applicationName;
            _attachDBFileName = connectionOptions._attachDBFileName;
            _currentLanguage = connectionOptions._currentLanguage;
            _dataSource = dataSource;
            _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
            _failoverPartner = connectionOptions._failoverPartner;
            _initialCatalog = connectionOptions._initialCatalog;
            _password = connectionOptions._password;
            _userID = connectionOptions._userID;
            _workstationId = connectionOptions._workstationId;
            _typeSystemVersion = connectionOptions._typeSystemVersion;
            _applicationIntent = connectionOptions._applicationIntent;
            _connectRetryCount = connectionOptions._connectRetryCount;
            _connectRetryInterval = connectionOptions._connectRetryInterval;

            ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
        }
示例#60
0
        public static SyntaxNode MethodInvocation(string name, MethodBase methodInfo, SyntaxNode instance, List <ArgumentSyntax> argumentList, TypeArgumentListSyntax typeArgumentList)
        {
            var sepList = SyntaxFactory.SeparatedList(argumentList);

            if (methodInfo == null)
            {
                return(SyntaxFactory.EmptyStatement());
            }

            var  propertyInfos = methodInfo.DeclaringType?.GetProperties();
            var  isSetAccessor = propertyInfos?.FirstOrDefault(prop => prop.GetSetMethod() == methodInfo);
            var  isGetAccessor = propertyInfos?.FirstOrDefault(prop => prop.GetGetMethod() == methodInfo);
            bool isProperty    = isSetAccessor != null || isGetAccessor != null;
            var  methodName    = methodInfo.Name;

            if (isProperty)
            {
                methodName = name.Substring(4);
            }

            bool             isGenericMethod        = methodInfo.IsGenericMethod;
            ExpressionSyntax finalExpressionSyntax  = null;
            ExpressionSyntax memberAccessExpression = instance == null?SyntaxFactory.IdentifierName(methodInfo.DeclaringType?.Name) : instance as ExpressionSyntax;

            if (!isProperty)
            {
                if (methodInfo.IsConstructor)
                {
                    finalExpressionSyntax = SyntaxFactory.ObjectCreationExpression(
                        TypeSystem.BuildTypeSyntax(methodInfo.DeclaringType))
                                            .WithArgumentList(SyntaxFactory.ArgumentList(sepList));
                }
                else
                {
                    SimpleNameSyntax genericName = isGenericMethod
                        ? (SimpleNameSyntax)SyntaxFactory.GenericName(
                        SyntaxFactory.Identifier(methodName))
                                                   .WithTypeArgumentList(typeArgumentList)
                        : SyntaxFactory.IdentifierName(methodName);

                    InvocationExpressionSyntax invocation = SyntaxFactory.InvocationExpression(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            memberAccessExpression,
                            genericName
                            ));
                    finalExpressionSyntax = invocation
                                            .WithArgumentList(SyntaxFactory.ArgumentList(sepList));
                }
            }
            else
            {
                if (isGetAccessor != null)
                {
                    if (isGetAccessor.GetIndexParameters().Length > 0)
                    {
                        finalExpressionSyntax = SyntaxFactory.ElementAccessExpression(
                            memberAccessExpression,
                            SyntaxFactory.BracketedArgumentList(sepList));
                    }
                    else
                    {
                        finalExpressionSyntax = SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            memberAccessExpression,
                            SyntaxFactory.IdentifierName(methodName));
                    }
                }
                else if (isSetAccessor != null)
                {
                    ExpressionSyntax left;
                    if (isSetAccessor.GetIndexParameters().Length > 0)
                    {
                        left = SyntaxFactory.ElementAccessExpression(memberAccessExpression, SyntaxFactory.BracketedArgumentList(
                                                                         SyntaxFactory.SeparatedList(argumentList.Take(argumentList.Count - 1))
                                                                         ));
                    }
                    else
                    {
                        left = SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            memberAccessExpression,
                            SyntaxFactory.IdentifierName(methodName));
                    }

                    finalExpressionSyntax = SyntaxFactory.AssignmentExpression(
                        SyntaxKind.SimpleAssignmentExpression,
                        left,
                        argumentList.Last().Expression);
                }
            }

            return(finalExpressionSyntax);
        }