Exemplo n.º 1
0
 internal static ImmutableArray<NamedTypeSymbol> ResolveExtensionContainers(PhpCompilation compilation)
 {
     return compilation.GetBoundReferenceManager()
         .ExplicitReferencesSymbols.OfType<PEAssemblySymbol>().Where(s => s.IsExtensionLibrary)
         .SelectMany(r => r.ExtensionContainers)
         .ToImmutableArray();
 }
Exemplo n.º 2
0
        public SourceAssemblySymbol(
            PhpCompilation compilation,
            string assemblySimpleName,
            string moduleName)
        {
            Debug.Assert(compilation != null);
            Debug.Assert(!String.IsNullOrWhiteSpace(assemblySimpleName));
            Debug.Assert(!String.IsNullOrWhiteSpace(moduleName));
            
            _compilation = compilation;
            _simpleName = assemblySimpleName;
            
            var moduleBuilder = new ArrayBuilder<ModuleSymbol>(1);

            moduleBuilder.Add(new SourceModuleSymbol(this, compilation.SourceSymbolTables, moduleName));

            //var importOptions = (compilation.Options.MetadataImportOptions == MetadataImportOptions.All) ?
            //    MetadataImportOptions.All : MetadataImportOptions.Internal;

            //foreach (PEModule netModule in netModules)
            //{
            //    moduleBuilder.Add(new PEModuleSymbol(this, netModule, importOptions, moduleBuilder.Count));
            //    // SetReferences will be called later by the ReferenceManager (in CreateSourceAssemblyFullBind for 
            //    // a fresh manager, in CreateSourceAssemblyReuseData for a reused one).
            //}

            _modules = moduleBuilder.ToImmutableAndFree();
        }
Exemplo n.º 3
0
 internal PENetModuleBuilder(
     PhpCompilation compilation,
     IModuleSymbol sourceModule,
     EmitOptions emitOptions,
     Microsoft.Cci.ModulePropertiesForSerialization serializationProperties,
     IEnumerable<ResourceDescription> manifestResources)
     : base(compilation, (Symbols.SourceModuleSymbol)sourceModule, serializationProperties, manifestResources, OutputKind.NetModule, emitOptions)
 {
 }
Exemplo n.º 4
0
        public SourceFileSymbol(PhpCompilation compilation, GlobalCode syntax)
        {
            Contract.ThrowIfNull(compilation);
            Contract.ThrowIfNull(syntax);

            _compilation = compilation;
            _syntax = syntax;
            _mainMethod = new SourceGlobalMethodSymbol(this);
        }
Exemplo n.º 5
0
        protected PEModuleBuilder(
            PhpCompilation compilation,
            SourceModuleSymbol sourceModule,
            Cci.ModulePropertiesForSerialization serializationProperties,
            IEnumerable<ResourceDescription> manifestResources,
            OutputKind outputKind,
            EmitOptions emitOptions)
        {
            Debug.Assert(sourceModule != null);
            Debug.Assert(serializationProperties != null);

            _compilation = compilation;
            _sourceModule = sourceModule;
            _serializationProperties = serializationProperties;
            this.ManifestResources = manifestResources;
            _outputKind = outputKind;
            _emitOptions = emitOptions;
            this.CompilationState = new CommonModuleCompilationState();
            _debugDocuments = new ConcurrentDictionary<string, Cci.DebugSourceDocument>(compilation.IsCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);
            _synthesized = new SynthesizedManager(this);

            AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, this);
        }
Exemplo n.º 6
0
 public override ITypeSymbol ResolveTypeSymbol(PhpCompilation compilation)
 {
     return(compilation.CoreTypes.Closure.Symbol);
 }
Exemplo n.º 7
0
 static IEnumerable <PEAssemblySymbol> GetExtensionLibraries(PhpCompilation compilation)
 => compilation
 .GetBoundReferenceManager()
 .ExplicitReferencesSymbols
 .OfType <PEAssemblySymbol>()
 .Where(s => s.IsExtensionLibrary);
Exemplo n.º 8
0
 internal static ImmutableArray <NamedTypeSymbol> ResolveExtensionContainers(PhpCompilation compilation)
 {
     return(GetExtensionLibraries(compilation)
            .SelectMany(r => r.ExtensionContainers)
            .ToImmutableArray());
 }
 public SynthesizedScriptTypeSymbol(PhpCompilation compilation)
 {
     _compilation = compilation;
 }
Exemplo n.º 10
0
 internal AnonymousTypeManager(PhpCompilation compilation)
 {
     Debug.Assert(compilation != null);
     this.Compilation = compilation;
 }
Exemplo n.º 11
0
 public SourcePharEntrySymbol(PhpCompilation compilation, PhpSyntaxTree syntaxTree)
     : base(compilation, syntaxTree)
 {
     Debug.Assert(syntaxTree.PharStubFile != null);
 }
Exemplo n.º 12
0
        public override Compilation CreateCompilation(TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger)
        {
            CompilerLogSource.Log.StartPhase(CompilationPhase.Parse.ToString());

            var parseOptions = Arguments.ParseOptions;

            // We compute script parse options once so we don't have to do it repeatedly in
            // case there are many script files.
            var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script);

            bool hadErrors = false;

            var sourceFiles = Arguments.SourceFiles;
            var trees       = new PhpSyntaxTree[sourceFiles.Length];

            if (Arguments.CompilationOptions.ConcurrentBuild)
            {
                Parallel.For(0, sourceFiles.Length, new Action <int>(i =>
                {
                    //NOTE: order of trees is important!!
                    trees[i] = ParseFile(consoleOutput, parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], errorLogger);
                }));
            }
            else
            {
                for (int i = 0; i < sourceFiles.Length; i++)
                {
                    //NOTE: order of trees is important!!
                    trees[i] = ParseFile(consoleOutput, parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], errorLogger);
                }
            }

            CompilerLogSource.Log.EndPhase();

            // If errors had been reported in ParseFile, while trying to read files, then we should simply exit.
            if (hadErrors)
            {
                return(null);
            }

            var diagnostics = new List <DiagnosticInfo>();

            var assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default;

            var xmlFileResolver    = new LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger);
            var sourceFileResolver = new LoggingSourceFileResolver(ImmutableArray <string> .Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger);

            MetadataReferenceResolver referenceDirectiveResolver;
            var resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, out referenceDirectiveResolver);

            if (ReportErrors(diagnostics, consoleOutput, errorLogger))
            {
                return(null);
            }

            var referenceResolver  = GetCommandLineMetadataReferenceResolver(touchedFilesLogger);
            var strongNameProvider = new LoggingStrongNameProvider(Arguments.KeyFileSearchPaths, touchedFilesLogger);

            var compilation = PhpCompilation.Create(
                Arguments.CompilationName,
                trees.WhereNotNull(),
                resolvedReferences,
                Arguments.CompilationOptions.
                WithMetadataReferenceResolver(referenceResolver).
                WithAssemblyIdentityComparer(assemblyIdentityComparer).
                WithStrongNameProvider(strongNameProvider).
                WithXmlReferenceResolver(xmlFileResolver).
                WithSourceReferenceResolver(sourceFileResolver)
                );

            return(compilation);
        }
Exemplo n.º 13
0
 public ResultTypeBinder(PhpCompilation compilation)
 {
     DeclaringCompilation = compilation ?? throw ExceptionUtilities.ArgumentNull(nameof(compilation));
 }
Exemplo n.º 14
0
 public GlobalSemantics(PhpCompilation compilation)
 {
     Contract.ThrowIfNull(compilation);
     _compilation = compilation;
 }
 /// <summary>
 /// Gets value indicating the extension is defined in compilation time.
 /// </summary>
 public static bool HasPhpExtenion(this PhpCompilation compilation, string extension_name)
 {
     return(compilation.GlobalSemantics.Extensions.Contains(extension_name, StringComparer.OrdinalIgnoreCase));
 }
Exemplo n.º 16
0
 /// <summary>
 /// Initializes new instance of <see cref="BoundTypeRefFactory"/>.
 /// </summary>
 /// <param name="compilation">Bound compilation.</param>
 public BoundTypeRefFactory(PhpCompilation compilation)
 {
     // TBD
 }
Exemplo n.º 17
0
 public GlobalSemantics(PhpCompilation compilation)
 {
     Contract.ThrowIfNull(compilation);
     _compilation = compilation;
 }
Exemplo n.º 18
0
        /// <summary>
        /// Gets type signature of the type [BaseType or NULL, Interface1, ..., InterfaceN]
        /// </summary>
        private static IEnumerable <Tuple <INamedTypeRef, NamedTypeSymbol> > ResolveTypeSignature(TypeDecl syntax, PhpCompilation compilation)
        {
            // base type or NULL
            if (syntax.BaseClass != null)   // a class with base
            {
                var baseTypeName = syntax.BaseClass.ClassName;

                yield return(new Tuple <INamedTypeRef, NamedTypeSymbol>(syntax.BaseClass, (NamedTypeSymbol)compilation.GlobalSemantics.GetType(baseTypeName)));
            }
            else if ((syntax.MemberAttributes & (PhpMemberAttributes.Static | PhpMemberAttributes.Interface)) != 0) // a static class or an interface
            {
                yield return(null);
            }
            else // a class without base
            {
                yield return(new Tuple <INamedTypeRef, NamedTypeSymbol>(null, compilation.CoreTypes.Object.Symbol));
            }

            // base interfaces
            var visited = new HashSet <QualifiedName>(); // set of visited interfaces

            foreach (var i in syntax.ImplementsList)
            {
                var qname = i.ClassName;
                if (visited.Add(qname))
                {
                    yield return(new Tuple <INamedTypeRef, NamedTypeSymbol>(i, (NamedTypeSymbol)compilation.GlobalSemantics.GetType(qname)));
                }
            }
        }
Exemplo n.º 19
0
 public Conversions(PhpCompilation compilation)
 {
     _compilation = compilation ?? throw ExceptionUtilities.ArgumentNull();
 }
Exemplo n.º 20
0
 /// <summary>
 /// Gets corresponding CLR type for the type reference.
 /// </summary>
 public INamedTypeSymbol GetTypeSymbol(PhpCompilation compilation)
 {
     return(compilation.CoreTypes.PhpArray.Symbol);
 }
Exemplo n.º 21
0
 public SynthesizedScriptTypeSymbol(PhpCompilation compilation)
 {
     _compilation = compilation;
 }
Exemplo n.º 22
0
 /// <summary>
 /// Gets corresponding CLR type for the type reference.
 /// </summary>
 public INamedTypeSymbol GetTypeSymbol(PhpCompilation compilation)
 {
     return(compilation.CoreTypes.Closure.Symbol);
 }
Exemplo n.º 23
0
        public CoreTypes(PhpCompilation compilation)
        {
            Contract.ThrowIfNull(compilation);
            _compilation = compilation;
            _table       = new Dictionary <string, CoreType>();

            Void                = Create(SpecialType.System_Void);
            Object              = Create(SpecialType.System_Object);
            Byte                = Create(SpecialType.System_Byte);
            Int32               = Create(SpecialType.System_Int32);
            Long                = Create(SpecialType.System_Int64);
            Double              = Create(SpecialType.System_Double);
            Boolean             = Create(SpecialType.System_Boolean);
            String              = Create(SpecialType.System_String);
            Exception           = CreateFromFullName(WellKnownTypes.GetMetadataName(WellKnownType.System_Exception));
            RuntimeTypeHandle   = Create(SpecialType.System_RuntimeTypeHandle);
            RuntimeMethodHandle = Create(SpecialType.System_RuntimeMethodHandle);

            PhpNumber                    = Create("PhpNumber");
            PhpAlias                     = Create("PhpAlias");
            PhpValue                     = Create("PhpValue");
            PhpString                    = Create("PhpString");
            PhpArray                     = Create("PhpArray");
            PhpResource                  = Create("PhpResource");
            IPhpArray                    = Create("IPhpArray");
            IPhpEnumerable               = Create("IPhpEnumerable");
            IPhpCallable                 = Create("IPhpCallable");
            IPhpConvertible              = Create("IPhpConvertible");
            PhpString_Blob               = Create("PhpString+Blob");
            IntStringKey                 = Create("IntStringKey");
            PhpHashtable                 = Create("PhpHashtable");
            ScriptDiedException          = Create("ScriptDiedException");
            Context                      = Create("Context");
            Operators                    = Create("Operators");
            Comparison                   = Create("Comparison");
            StrictComparison             = Create("StrictComparison");
            Convert                      = Create("Convert");
            StrictConvert                = Create("StrictConvert");
            PhpException                 = Create("PhpException");
            ScriptAttribute              = Create("ScriptAttribute");
            PhpTraitAttribute            = Create(PhpTraitAttributeName);
            PharAttribute                = Create("PharAttribute");
            PhpTypeAttribute             = Create("PhpTypeAttribute");
            PhpHiddenAttribute           = Create("PhpHiddenAttribute");
            ImportValueAttribute         = Create("ImportValueAttribute");
            DummyFieldsOnlyCtor          = Create("DummyFieldsOnlyCtor");
            PhpFieldsOnlyCtorAttribute   = Create(PhpFieldsOnlyCtorAttributeName);
            DefaultValueAttribute        = Create("DefaultValueAttribute");
            PhpCustomAtribute            = Create(nameof(PhpCustomAtribute));
            PhpMemberVisibilityAttribute = Create(PhpMemberVisibilityAttributeName);
            NullableAttribute            = CreateFromFullName("System.Runtime.CompilerServices.NullableAttribute");
            NullableContextAttribute     = CreateFromFullName("System.Runtime.CompilerServices.NullableContextAttribute");
            IStaticInit                  = Create("IStaticInit");
            RoutineInfo                  = Create("Reflection.RoutineInfo");
            IndirectLocal                = Create("IndirectLocal");
            stdClass                     = CreateFromFullName("stdClass");
            ArrayAccess                  = CreateFromFullName("ArrayAccess");
            Closure                      = CreateFromFullName("Closure");

            BinderFactory       = Create("Dynamic.BinderFactory");
            GetClassConstBinder = Create("Dynamic.GetClassConstBinder");
            GetFieldBinder      = Create("Dynamic.GetFieldBinder");
            SetFieldBinder      = Create("Dynamic.SetFieldBinder");
            AccessMask          = CreateFromFullName("Pchp.CodeAnalysis.Semantics.AccessMask");

            Dynamic_NameParam_T         = Create("Dynamic.NameParam`1");
            Dynamic_TargetTypeParam     = Create("Dynamic.TargetTypeParam");
            Dynamic_LateStaticTypeParam = Create("Dynamic.LateStaticTypeParam");
            Dynamic_CallerTypeParam     = Create("Dynamic.CallerTypeParam");
            Dynamic_UnpackingParam_T    = Create("Dynamic.UnpackingParam`1");

            RuntimeChain_ChainEnd       = Create("Dynamic.RuntimeChain.ChainEnd");
            RuntimeChain_Value_T        = Create("Dynamic.RuntimeChain.Value`1");
            RuntimeChain_Property_T     = Create("Dynamic.RuntimeChain.Property`1");
            RuntimeChain_ArrayItem_T    = Create("Dynamic.RuntimeChain.ArrayItem`1");
            RuntimeChain_ArrayNewItem_T = Create("Dynamic.RuntimeChain.ArrayNewItem`1");

            PhpTypeInfoExtension = Create("Reflection.PhpTypeInfoExtension");
            PhpTypeInfo          = Create("Reflection.PhpTypeInfo");
            CommonPhpArrayKeys   = Create("CommonPhpArrayKeys");

            Iterator    = CreateFromFullName("Iterator");
            Traversable = CreateFromFullName("Traversable");
            Stringable  = CreateFromFullName("Stringable");
            Generator   = CreateFromFullName("Generator");
            GeneratorStateMachineDelegate = CreateFromFullName("GeneratorStateMachineDelegate");

            MainDelegate = Create("Context+MainDelegate");
            IntPtr       = CreateFromFullName("System.IntPtr");
        }
Exemplo n.º 24
0
 /// <summary>
 /// Gets corresponding CLR type for the type reference.
 /// </summary>
 public INamedTypeSymbol GetTypeSymbol(PhpCompilation compilation)
 {
     return(compilation.GlobalSemantics.GetType(QualifiedName) ?? compilation.CoreTypes.Object.Symbol);
 }
Exemplo n.º 25
0
 public static SourceFileSymbol Create(PhpCompilation compilation, PhpSyntaxTree syntaxTree)
 {
     return(syntaxTree.IsPharEntry
         ? new SourcePharEntrySymbol(compilation, syntaxTree)
         : new SourceFileSymbol(compilation, syntaxTree));
 }
Exemplo n.º 26
0
        public override ITypeSymbol ResolveTypeSymbol(PhpCompilation compilation)
        {
            if (ResolvedType.IsValidType() && !ResolvedType.IsUnreachable)
            {
                return(ResolvedType);
            }

            TypeSymbol type = null;

            if (_self != null)
            {
                if (_self.FullName == _qname)
                {
                    type = _self;
                }
                else if (_self.BaseType is IPhpTypeSymbol phpt && phpt.FullName == _qname)
                {
                    type = _self.BaseType;
                }
            }

            if (type == null)
            {
                type = (TypeSymbol)compilation.GlobalSemantics.ResolveType(_qname);
            }

            if (type is AmbiguousErrorTypeSymbol ambiguous && _routine != null)
            {
                TypeSymbol best = null;

                // choose the one declared in this file unconditionally
                foreach (var x in ambiguous
                         .CandidateSymbols
                         .Cast <TypeSymbol>()
                         .Where(t => !t.IsUnreachable)
                         .Where(x => x is SourceTypeSymbol srct && !srct.Syntax.IsConditional && srct.ContainingFile == _routine.ContainingFile))
                {
                    if (best == null)
                    {
                        best = x;
                    }
                    else
                    {
                        best = null;
                        break;
                    }
                }

                if (best != null)
                {
                    type = (NamedTypeSymbol)best;
                }
            }

            // translate trait prototype to constructed trait type
            if (type.IsTraitType())
            {
                // <!TSelf> -> <T<Object>>
                var t = (NamedTypeSymbol)type;
                type = t.Construct(t.Construct(compilation.CoreTypes.Object));
            }

            //
            return(ResolvedType = type);
        }
Exemplo n.º 27
0
        public CoreTypes(PhpCompilation compilation)
        {
            Contract.ThrowIfNull(compilation);
            _compilation = compilation;
            _table       = new Dictionary <string, CoreType>();

            Void                = Create(SpecialType.System_Void);
            Object              = Create(SpecialType.System_Object);
            Int32               = Create(SpecialType.System_Int32);
            Long                = Create(SpecialType.System_Int64);
            Double              = Create(SpecialType.System_Double);
            Boolean             = Create(SpecialType.System_Boolean);
            String              = Create(SpecialType.System_String);
            Exception           = CreateFromFullName(WellKnownTypes.GetMetadataName(WellKnownType.System_Exception));
            RuntimeTypeHandle   = Create(SpecialType.System_RuntimeTypeHandle);
            RuntimeMethodHandle = Create(SpecialType.System_RuntimeMethodHandle);

            PhpNumber                    = Create("PhpNumber");
            PhpAlias                     = Create("PhpAlias");
            PhpValue                     = Create("PhpValue");
            PhpString                    = Create("PhpString");
            PhpArray                     = Create("PhpArray");
            PhpResource                  = Create("PhpResource");
            IPhpArray                    = Create("IPhpArray");
            IPhpEnumerable               = Create("IPhpEnumerable");
            IPhpCallable                 = Create("IPhpCallable");
            IPhpConvertible              = Create("IPhpConvertible");
            IntStringKey                 = Create("IntStringKey");
            PhpHashtable                 = Create("PhpHashtable");
            ScriptDiedException          = Create("ScriptDiedException");
            Context                      = Create("Context");
            Operators                    = Create("Operators");
            Comparison                   = Create("Comparison");
            StrictComparison             = Create("StrictComparison");
            Convert                      = Create("Convert");
            PhpException                 = Create("PhpException");
            ScriptAttribute              = Create("ScriptAttribute");
            PhpTraitAttribute            = Create(PhpTraitAttributeName);
            PhpTypeAttribute             = Create("PhpTypeAttribute");
            PhpHiddenAttribute           = Create("PhpHiddenAttribute");
            PhpFieldsOnlyCtorAttribute   = Create(PhpFieldsOnlyCtorAttributeName);
            NotNullAttribute             = Create("NotNullAttribute");
            PhpMemberVisibilityAttribute = Create(PhpMemberVisibilityAttributeName);
            IStaticInit                  = Create("IStaticInit");
            RoutineInfo                  = Create("Reflection.RoutineInfo");
            stdClass                     = CreateFromFullName("stdClass");
            ArrayAccess                  = CreateFromFullName("ArrayAccess");
            Closure                      = CreateFromFullName("Closure");

            BinderFactory       = Create("Dynamic.BinderFactory");
            GetClassConstBinder = Create("Dynamic.GetClassConstBinder");
            GetFieldBinder      = Create("Dynamic.GetFieldBinder");
            SetFieldBinder      = Create("Dynamic.SetFieldBinder");
            AccessMask          = CreateFromFullName("Pchp.CodeAnalysis.Semantics.AccessMask");

            Dynamic_NameParam_T      = Create("Dynamic.NameParam`1");
            Dynamic_TargetTypeParam  = Create("Dynamic.TargetTypeParam");
            Dynamic_CallerTypeParam  = Create("Dynamic.CallerTypeParam");
            Dynamic_UnpackingParam_T = Create("Dynamic.UnpackingParam`1");

            PhpTypeInfoExtension = Create("Reflection.PhpTypeInfoExtension");
            PhpTypeInfo          = Create("Reflection.PhpTypeInfo");

            Iterator  = CreateFromFullName("Iterator");
            Generator = CreateFromFullName("Generator");
            GeneratorStateMachineDelegate = CreateFromFullName("GeneratorStateMachineDelegate");

            IntPtr = CreateFromFullName("System.IntPtr");
        }
Exemplo n.º 28
0
 public override ITypeSymbol ResolveTypeSymbol(PhpCompilation compilation)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 29
0
 public GlobalSymbolProvider(PhpCompilation compilation)
 {
     Contract.ThrowIfNull(compilation);
     _compilation = compilation;
     _next        = new SourceSymbolProvider(compilation.SourceSymbolCollection);
 }
Exemplo n.º 30
0
 /// <summary>
 /// Init test class.
 /// </summary>
 public DiagnosticTest(ITestOutputHelper output)
 {
     _output           = output;
     _emptyCompilation = CreateEmptyCompilation();
 }
Exemplo n.º 31
0
 public GlobalSymbolProvider(PhpCompilation compilation)
 {
     _compilation = compilation ?? throw new ArgumentNullException(nameof(compilation));
     _next        = new SourceSymbolProvider(compilation.SourceSymbolCollection);
 }
Exemplo n.º 32
0
 internal TypeRefContext(PhpCompilation compilation, SourceTypeSymbol selfType, SourceTypeSymbol thisType)
 {
     _compilation = compilation ?? throw ExceptionUtilities.ArgumentNull(nameof(compilation));
     _selfType    = selfType;
     _thisType    = thisType;
 }
Exemplo n.º 33
0
 static IEnumerable <NamedTypeSymbol> ResolveExtensionContainers(PhpCompilation compilation)
 {
     return(GetExtensionLibraries(compilation)
            .SelectMany(r => r.ExtensionContainers));
 }
Exemplo n.º 34
0
        public static ConstantValue TryGetConstantValue(PhpCompilation compilation, AST.Expression value)
        {
            if (value is AST.Literal) return CreateConstant((AST.Literal)value);
            if (value is AST.GlobalConstUse) return CreateConstant((AST.GlobalConstUse)value);

            return null;
        }
Exemplo n.º 35
0
        public override ITypeSymbol ResolveTypeSymbol(PhpCompilation compilation)
        {
            if (ResolvedType.IsValidType() && !ResolvedType.IsUnreachable)
            {
                return(ResolvedType);
            }

            TypeSymbol type = null;

            if (_self != null)
            {
                if (_self.FullName == ClassName)
                {
                    type = _self;
                }
                else if (_self.BaseType != null && _self.BaseType.PhpQualifiedName() == ClassName)
                {
                    type = _self.BaseType;
                }
            }

            if (type == null)
            {
                type = (_arity <= 0)
                 ? (TypeSymbol)compilation.GlobalSemantics.ResolveType(ClassName)
                       // generic types only exist in external references, use this method to resolve the symbol including arity (needs metadataname instead of QualifiedName)
                 : compilation.GlobalSemantics.GetTypeFromNonExtensionAssemblies(MetadataHelpers.ComposeAritySuffixedMetadataName(ClassName.ClrName(), _arity));
            }

            var containingFile = _routine?.ContainingFile ?? _self?.ContainingFile;

            if (type is AmbiguousErrorTypeSymbol ambiguous && containingFile != null)
            {
                TypeSymbol best = null;

                // choose the one declared in this file unconditionally
                foreach (var x in ambiguous
                         .CandidateSymbols
                         .Cast <TypeSymbol>()
                         .Where(t => !t.IsUnreachable)
                         .Where(x => x is SourceTypeSymbol srct && !srct.Syntax.IsConditional && srct.ContainingFile == containingFile))
                {
                    if (best == null)
                    {
                        best = x;
                    }
                    else
                    {
                        best = null;
                        break;
                    }
                }

                if (best != null)
                {
                    type = (NamedTypeSymbol)best;
                }
            }

            // translate trait prototype to constructed trait type
            if (type.IsTraitType())
            {
                // <!TSelf> -> <T<Object>>
                var t = (NamedTypeSymbol)type;
                type = t.Construct(t.Construct(compilation.CoreTypes.Object));
            }

            //
            return(ResolvedType = type);
        }
Exemplo n.º 36
0
 public PopulatorVisitor(PhpCompilation compilation, SourceDeclarations tables)
 {
     _tables = tables;
     _compilation = compilation;
 }
Exemplo n.º 37
0
 internal TypeRefContext(PhpCompilation compilation, SourceTypeSymbol selfType)
     : this(compilation, selfType, thisType : selfType)
 {
 }
Exemplo n.º 38
0
        void EmitInit(Emit.PEModuleBuilder module, DiagnosticBag diagnostic, PhpCompilation compilation, SynthesizedStaticLocHolder holder, BoundExpression initializer)
        {
            var loctype = holder.ValueField.Type;

            bool requiresContext = initializer != null && initializer.RequiresContext;

            if (requiresContext)
            {
                // emit Init only if it needs Context

                holder.EmitInit(module, (il) =>
                {
                    var cg = new CodeGenerator(il, module, diagnostic, OptimizationLevel.Release, false,
                        holder.ContainingType, new ArgPlace(compilation.CoreTypes.Context, 1), new ArgPlace(holder, 0));

                    var valuePlace = new FieldPlace(cg.ThisPlaceOpt, holder.ValueField);
                    
                    // Template: this.value = <initilizer>;

                    valuePlace.EmitStorePrepare(il);
                    cg.EmitConvert(initializer, valuePlace.TypeOpt);                    
                    valuePlace.EmitStore(il);

                    //
                    il.EmitRet(true);
                });
            }

            // default .ctor
            holder.EmitCtor(module, (il) =>
            {
                if (!requiresContext)
                {
                    // emit default value only if it won't be initialized by Init above

                    var cg = new CodeGenerator(il, module, diagnostic, OptimizationLevel.Release, false,
                        holder.ContainingType, null, new ArgPlace(holder, 0));

                    var valuePlace = new FieldPlace(cg.ThisPlaceOpt, holder.ValueField);

                    // Template: this.value = default(T);

                    valuePlace.EmitStorePrepare(il);
                    if (initializer != null)
                    {
                        cg.EmitConvert(initializer, valuePlace.TypeOpt);
                    }
                    else
                    {
                        cg.EmitLoadDefault(valuePlace.TypeOpt, 0);
                    }
                    valuePlace.EmitStore(il);
                }

                //
                il.EmitRet(true);
            });
        }
Exemplo n.º 39
0
        public DynamicOperationFactory(CodeGenerator cg, NamedTypeSymbol container)
        {
            Contract.ThrowIfNull(cg);

            _cg = cg;
            _compilation = cg.DeclaringCompilation;
            _container = container;
        }
Exemplo n.º 40
0
 public abstract ITypeSymbol ResolveTypeSymbol(PhpCompilation compilation);
Exemplo n.º 41
0
        public override Compilation CreateCompilation(TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger, ImmutableArray <AnalyzerConfigOptionsResult> analyzerConfigOptions)
        {
            bool hadErrors   = false;
            var  sourceFiles = Arguments.SourceFiles;

            IEnumerable <PhpSyntaxTree> sourceTrees;
            var resources = Enumerable.Empty <ResourceDescription>();

            using (Arguments.CompilationOptions.EventSources.StartMetric("parse"))
            {
                // PARSE

                var parseOptions = Arguments.ParseOptions;

                // NOTE: order of trees is important!!
                var trees     = new PhpSyntaxTree[sourceFiles.Length];
                var pharFiles = new List <(int index, ParsedSource phar)>();

                void ProcessParsedSource(int index, ParsedSource parsed)
                {
                    if (parsed.Manifest == null)
                    {
                        trees[index] = parsed.SyntaxTree;
                    }
                    else
                    {
                        pharFiles.Add((index, parsed));
                    }
                }

                // We compute script parse options once so we don't have to do it repeatedly in
                // case there are many script files.
                var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script);

                if (Arguments.CompilationOptions.ConcurrentBuild)
                {
                    Parallel.For(0, sourceFiles.Length, new Action <int>(i =>
                    {
                        ProcessParsedSource(i, ParseFile(consoleOutput, parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], errorLogger));
                    }));
                }
                else
                {
                    for (int i = 0; i < sourceFiles.Length; i++)
                    {
                        ProcessParsedSource(i, ParseFile(consoleOutput, parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], errorLogger));
                    }
                }

                // flattern trees and pharFiles

                if (pharFiles == null || pharFiles.Count == 0)
                {
                    sourceTrees = trees;
                }
                else
                {
                    var treesList = new List <PhpSyntaxTree>(trees);

                    // enlist phars from the end (index)
                    foreach (var f in pharFiles.OrderByDescending(x => x.index))
                    {
                        treesList[f.index] = f.phar.SyntaxTree; // phar stub, may be null
                        treesList.InsertRange(f.index + 1, f.phar.Trees);

                        // add content files
                        if (f.phar.Resources != null)
                        {
                            resources = resources.Concat(f.phar.Resources);
                        }
                    }

                    sourceTrees = treesList;
                }

                // END PARSE
            }

            // If errors had been reported in ParseFile, while trying to read files, then we should simply exit.
            if (hadErrors)
            {
                return(null);
            }

            var diagnostics = new List <DiagnosticInfo>();

            var assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default;

            var xmlFileResolver    = new LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger);
            var sourceFileResolver = new LoggingSourceFileResolver(ImmutableArray <string> .Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger);

            MetadataReferenceResolver referenceDirectiveResolver;
            var resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, out referenceDirectiveResolver);

            if (ReportDiagnostics(diagnostics, consoleOutput, errorLogger))
            {
                return(null);
            }

            //
            var referenceResolver  = GetCommandLineMetadataReferenceResolver(touchedFilesLogger);
            var loggingFileSystem  = new LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory);
            var strongNameProvider = Arguments.GetStrongNameProvider(loggingFileSystem);

            var compilation = PhpCompilation.Create(
                Arguments.CompilationName,
                sourceTrees.WhereNotNull(),
                resolvedReferences,
                resources: resources,
                options: Arguments.CompilationOptions.
                WithMetadataReferenceResolver(referenceResolver).
                WithAssemblyIdentityComparer(assemblyIdentityComparer).
                WithStrongNameProvider(strongNameProvider).
                WithXmlReferenceResolver(xmlFileResolver).
                WithSourceReferenceResolver(sourceFileResolver)
                );

            return(compilation);
        }
Exemplo n.º 42
0
        internal void PopulateTables(PhpCompilation compilation, IEnumerable<SourceUnit>/**/trees)
        {
            Contract.ThrowIfNull(compilation);
            Contract.ThrowIfNull(trees);

            _baseDirectory = compilation.Options.BaseDirectory;

            var visitor = new PopulatorVisitor(compilation, this);
            trees.ForEach(visitor.VisitSourceUnit);
        }