Beispiel #1
0
        private void GenerateTypesAndUsings(ScriptBlockAst rootForDefiningTypesAndUsings, List<Expression> exprs)
        {
            // We don't postpone load assemblies, import modules from 'using' to the moment, when enclosed scriptblock is executed.
            // We do loading, when root of the script is compiled.
            // This allow us to avoid creating 10 different classes in this situation:
            // 1..10 | % { class C {} }
            // But it's possible that we are loading something from the codepaths that we never execute.

            // If Parent of rootForDefiningTypesAndUsings is not null, then we already defined all types, when Visit a parent ScriptBlock
            if (rootForDefiningTypesAndUsings.Parent == null)
            {
                if (rootForDefiningTypesAndUsings.UsingStatements.Any())
                {
                    bool allUsingsAreNamespaces = rootForDefiningTypesAndUsings.UsingStatements.All(us => us.UsingStatementKind == UsingStatementKind.Namespace);
                    GenerateLoadUsings(rootForDefiningTypesAndUsings.UsingStatements, allUsingsAreNamespaces, exprs);
                }

                TypeDefinitionAst[] typeAsts =
                    rootForDefiningTypesAndUsings.FindAll(ast => ast is TypeDefinitionAst, true)
                        .Cast<TypeDefinitionAst>()
                        .ToArray();

                if (typeAsts.Length > 0)
                {
                    var assembly = DefinePowerShellTypes(rootForDefiningTypesAndUsings, typeAsts);
                    exprs.Add(Expression.Call(CachedReflectionInfo.TypeOps_SetAssemblyDefiningPSTypes,
                        _functionContext, Expression.Constant(assembly)));

                    exprs.Add(Expression.Call(CachedReflectionInfo.TypeOps_InitPowerShellTypesAtRuntime,
                        Expression.Constant(typeAsts)));
                }
            }

            Dictionary<string, TypeDefinitionAst> typesToAddToScope =
                rootForDefiningTypesAndUsings.FindAll(ast => ast is TypeDefinitionAst, false)
                    .Cast<TypeDefinitionAst>()
                    .ToDictionary(type => type.Name);
            if (typesToAddToScope.Count > 0)
            {
                exprs.Add(Expression.Call(CachedReflectionInfo.TypeOps_AddPowerShellTypesToTheScope,
                    Expression.Constant(typesToAddToScope), _executionContextParameter));
            }
        }