Esempio n. 1
0
 public BoundGenericClassTypeRef(IBoundTypeRef targetType, ImmutableArray <BoundTypeRef> typeArguments)
 {
     _targetType    = targetType ?? throw ExceptionUtilities.ArgumentNull(nameof(targetType));
     _typeArguments = typeArguments;
 }
Esempio n. 2
0
        protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            // Ensure this event which routes text log messages to ETW is not handled by
            // event listeners
            if (eventData.EventId == (int)EventId.TextLogEtwOnly)
            {
                return;
            }

            // If diagnostic events are enabled, we may see events not matching the NormalKeywords.
            // In that case we further filter based on the event's Task. See EnableTaskDiagnostics.
            // Keywords == 0 acts like a wildcard (all keywords); see EventSource sources. For some reason EventSource sets some top bits.
            if (unchecked ((uint)eventData.Keywords) != 0)
            {
                if ((eventData.Keywords & NormalKeywords) == 0 &&
                    (eventData.Keywords & DiagnosticsKeywords) != 0 &&
                    (eventData.Task > Events.Tasks.Max || !m_enableTaskDiagnostics[unchecked ((int)eventData.Task)]))
                {
                    return;
                }

                if ((eventData.Keywords & Events.Keywords.SelectivelyEnabled) != 0 &&
                    (m_eventMask?.IsSelectivelyEnabled != true))
                {
                    // Exclude any event which is selectively enabled if this event listener does
                    // not selectively enable events (i.e. specify specific event ids which should not be
                    // excluded)
                    return;
                }
            }

            // Out-of-band messages from EventListener.ReportOutOfBandMessage end up with event ID 0.
            // We don't allow these messages to be upgraded to errors by the WarningMapper since they typically
            // are not actionable.
            bool       isOutOfBand       = eventData.EventId == 0;
            EventLevel level             = isOutOfBand ? EventLevel.Warning : eventData.Level;
            bool       suppressedWarning = false;

            if (level == EventLevel.Warning && !isOutOfBand)
            {
                if (m_warningMapper != null)
                {
                    switch (m_warningMapper(eventData.EventId))
                    {
                    case WarningState.AsError:
                    {
                        level = EventLevel.Error;
                        break;
                    }

                    case WarningState.AsWarning:
                    {
                        // nothing to do
                        break;
                    }

                    case WarningState.Suppressed:
                    {
                        suppressedWarning = true;
                        break;
                    }
                    }
                }
            }

            // Bail out if the event is not enabled based on the event mask
            if (m_eventMask != null && !m_eventMask.IsEnabled(level, eventData.EventId))
            {
                return;
            }

            // Derived listeners don't need to worry about locking, we do it here...
            lock (m_lock)
            {
                try
                {
                    if (m_disabledDueToDiskWriteFailure)
                    {
                        return;
                    }

                    if (m_limitToCriticalLevelOnly && level != EventLevel.Critical)
                    {
                        return;
                    }

                    // dispatch to the appropriate handler method
                    switch (level)
                    {
                    case EventLevel.Critical:
                    {
                        OnCritical(eventData);
                        break;
                    }

                    case EventLevel.Error:
                    {
                        OnError(eventData);
                        break;
                    }

                    case EventLevel.Informational:
                    {
                        OnInformational(eventData);
                        break;
                    }

                    case EventLevel.LogAlways:
                    {
                        OnAlways(eventData);
                        break;
                    }

                    case EventLevel.Verbose:
                    {
                        OnVerbose(eventData);
                        break;
                    }

                    default:
                    {
                        Contract.Assert(level == EventLevel.Warning);

                        if (isOutOfBand)
                        {
                            OnEventSourceInternalWarning(eventData);
                        }
                        else
                        {
                            if (!suppressedWarning)
                            {
                                OnWarning(eventData);
                            }
                            else
                            {
                                OnSuppressedWarning(eventData);
                            }
                        }

                        break;
                    }
                    }
                }
                catch (Exception ex)
                {
                    // Event listeners have an unfortunate distinction of being very useful for reporting terminal failures (i.e., in an unhandled exception handler).
                    // So, we need graceful failure in the event of systemic inability to write to some listeners (e.g. out of disk space): The unhandled exception handler
                    // should, in that circumstance, be able to write to any not-yet-broken listeners.
                    if (m_disabledDueToDiskWriteFailureEventHandler != null &&
                        ExceptionUtilities.AnalyzeExceptionRootCause(ex) == ExceptionRootCause.OutOfDiskSpace)
                    {
                        m_disabledDueToDiskWriteFailure = true;
                        OnDisabledDueToDiskWriteFailure();
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Emits address as in &amp;
        ///
        /// May introduce a temp which it will return. (otherwise returns null)
        /// </summary>
        private LocalDefinition EmitAddress(BoundExpression expression, AddressKind addressKind)
        {
            switch (expression.Kind)
            {
            case BoundKind.RefValueOperator:
                EmitRefValueAddress((BoundRefValueOperator)expression);
                break;

            case BoundKind.Local:
                return(EmitLocalAddress((BoundLocal)expression, addressKind));

            case BoundKind.Dup:
                Debug.Assert(((BoundDup)expression).RefKind != RefKind.None, "taking address of a stack value?");
                return(EmitDupAddress((BoundDup)expression, addressKind));

            case BoundKind.ConditionalReceiver:
                // do nothing receiver ref must be already pushed
                Debug.Assert(!expression.Type.IsReferenceType);
                Debug.Assert(!expression.Type.IsValueType || expression.Type.IsNullableType());
                break;

            case BoundKind.ComplexConditionalReceiver:
                EmitComplexConditionalReceiverAddress((BoundComplexConditionalReceiver)expression);
                break;

            case BoundKind.Parameter:
                return(EmitParameterAddress((BoundParameter)expression, addressKind));

            case BoundKind.FieldAccess:
                return(EmitFieldAddress((BoundFieldAccess)expression, addressKind));

            case BoundKind.ArrayAccess:
                if (!HasHome(expression, addressKind))
                {
                    goto default;
                }

                EmitArrayElementAddress((BoundArrayAccess)expression, addressKind);
                break;

            case BoundKind.ThisReference:
                Debug.Assert(expression.Type.IsValueType, "only value types may need a ref to this");
                Debug.Assert(HasHome(expression, addressKind));
                _builder.EmitOpCode(ILOpCode.Ldarg_0);
                break;

            case BoundKind.PreviousSubmissionReference:
                // script references are lowered to a this reference and a field access
                throw ExceptionUtilities.UnexpectedValue(expression.Kind);

            case BoundKind.BaseReference:
                Debug.Assert(false, "base is always a reference type, why one may need a reference to it?");
                break;

            case BoundKind.Sequence:
                return(EmitSequenceAddress((BoundSequence)expression, addressKind));

            case BoundKind.PointerIndirectionOperator:
                // The address of a dereferenced address is that address.
                BoundExpression operand = ((BoundPointerIndirectionOperator)expression).Operand;
                Debug.Assert(operand.Type.IsPointerType());
                EmitExpression(operand, used: true);
                break;

            case BoundKind.PseudoVariable:
                EmitPseudoVariableAddress((BoundPseudoVariable)expression);
                break;

            case BoundKind.Call:
                var call          = (BoundCall)expression;
                var methodRefKind = call.Method.RefKind;

                if (methodRefKind == RefKind.Ref ||
                    (IsReadOnly(addressKind) && methodRefKind == RefKind.RefReadOnly))
                {
                    EmitCallExpression(call, UseKind.UsedAsAddress);
                    break;
                }

                goto default;

            case BoundKind.DefaultExpression:
                var type = expression.Type;

                var temp = this.AllocateTemp(type, expression.Syntax);
                _builder.EmitLocalAddress(temp);                      //  ldloca temp
                _builder.EmitOpCode(ILOpCode.Dup);                    //  dup
                _builder.EmitOpCode(ILOpCode.Initobj);                //  initobj  <type>
                EmitSymbolToken(type, expression.Syntax);
                return(temp);

            case BoundKind.ConditionalOperator:
                if (!HasHome(expression, addressKind))
                {
                    goto default;
                }

                EmitConditionalOperatorAddress((BoundConditionalOperator)expression, addressKind);
                break;

            case BoundKind.AssignmentOperator:
                var assignment = (BoundAssignmentOperator)expression;
                if (assignment.RefKind == RefKind.None)
                {
                    goto default;
                }

                throw ExceptionUtilities.UnexpectedValue(assignment.RefKind);

            case BoundKind.ThrowExpression:
                // emit value or address is the same here.
                EmitExpression(expression, used: true);
                return(null);

            default:
                Debug.Assert(!HasHome(expression, addressKind));
                return(EmitAddressOfTempClone(expression));
            }

            return(null);
        }
Esempio n. 4
0
        internal BoundExpression SetInferredType(TypeSymbol type, Binder binderOpt, DiagnosticBag diagnosticsOpt)
        {
            Debug.Assert(binderOpt != null || (object)type != null);
            Debug.Assert(this.Syntax.Kind() == SyntaxKind.SingleVariableDesignation ||
                         (this.Syntax.Kind() == SyntaxKind.DeclarationExpression &&
                          ((DeclarationExpressionSyntax)this.Syntax).Designation.Kind() == SyntaxKind.SingleVariableDesignation));

            bool inferenceFailed = ((object)type == null);

            if (inferenceFailed)
            {
                type = binderOpt.CreateErrorType("var");
            }

            switch (this.VariableSymbol.Kind)
            {
            case SymbolKind.Local:
                var localSymbol = (SourceLocalSymbol)this.VariableSymbol;

                if (diagnosticsOpt != null)
                {
                    if (inferenceFailed)
                    {
                        ReportInferenceFailure(diagnosticsOpt);
                    }
                    else
                    {
                        SyntaxNode typeOrDesignationSyntax = this.Syntax.Kind() == SyntaxKind.DeclarationExpression ?
                                                             ((DeclarationExpressionSyntax)this.Syntax).Type :
                                                             this.Syntax;

                        Binder.CheckRestrictedTypeInAsync(localSymbol.ContainingSymbol, type, diagnosticsOpt, typeOrDesignationSyntax);
                    }
                }

                localSymbol.SetType(type);
                return(new BoundLocal(this.Syntax, localSymbol, isDeclaration: true, constantValueOpt: null, type: type, hasErrors: this.HasErrors || inferenceFailed));

            case SymbolKind.Field:
                var fieldSymbol          = (GlobalExpressionVariable)this.VariableSymbol;
                var inferenceDiagnostics = DiagnosticBag.GetInstance();

                if (inferenceFailed)
                {
                    ReportInferenceFailure(inferenceDiagnostics);
                }

                type = fieldSymbol.SetType(type, inferenceDiagnostics);
                inferenceDiagnostics.Free();

                return(new BoundFieldAccess(this.Syntax,
                                            this.ReceiverOpt,
                                            fieldSymbol,
                                            null,
                                            LookupResultKind.Viable,
                                            isDeclaration: true,
                                            type: type,
                                            hasErrors: this.HasErrors || inferenceFailed));

            default:
                throw ExceptionUtilities.UnexpectedValue(this.VariableSymbol.Kind);
            }
        }
Esempio n. 5
0
        internal override EmbeddedMethod EmbedMethod(
            EmbeddedType type,
            MethodSymbol method,
            CSharpSyntaxNode syntaxNodeOpt,
            DiagnosticBag diagnostics)
        {
            Debug.Assert(method.IsDefinition);
            Debug.Assert(!method.IsDefaultValueTypeConstructor());

            EmbeddedMethod embedded = new EmbeddedMethod(type, method);
            EmbeddedMethod cached   = EmbeddedMethodsMap.GetOrAdd(method, embedded);

            if (embedded != cached)
            {
                return(cached);
            }

            // We do not expect this method to be called on a different thread once GetTypes is called.
            // Therefore, the following check can be as simple as:
            Debug.Assert(!IsFrozen, "Set of embedded methods is frozen.");

            // Embed types referenced by this method declaration.
            EmbedReferences(embedded, syntaxNodeOpt, diagnostics);

            switch (type.UnderlyingNamedType.TypeKind)
            {
            case TypeKind.Struct:
            case TypeKind.Enum:
                // ERRID.ERR_InvalidStructMemberNoPIA1/ERR_InteropStructContainsMethods
                ReportNotEmbeddableSymbol(ErrorCode.ERR_InteropStructContainsMethods, type.UnderlyingNamedType, syntaxNodeOpt, diagnostics, this);
                break;

            default:
                if (Cci.Extensions.HasBody(embedded))
                {
                    // ERRID.ERR_InteropMethodWithBody1/ERR_InteropMethodWithBody
                    Error(diagnostics, ErrorCode.ERR_InteropMethodWithBody, syntaxNodeOpt, method.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
                }
                break;
            }

            // If this proc happens to belong to a property/event, we should include the property/event as well.
            Symbol propertyOrEvent = method.AssociatedSymbol;

            if ((object)propertyOrEvent != null)
            {
                switch (propertyOrEvent.Kind)
                {
                case SymbolKind.Property:
                    EmbedProperty(type, (PropertySymbol)propertyOrEvent, syntaxNodeOpt, diagnostics);
                    break;

                case SymbolKind.Event:
                    EmbedEvent(type, (EventSymbol)propertyOrEvent, syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding: false);
                    break;

                default:
                    throw ExceptionUtilities.UnexpectedValue(propertyOrEvent.Kind);
                }
            }

            return(embedded);
        }
Esempio n. 6
0
        public override bool Execute()
        {
#if DEBUG
            var debugRestoreTask = Environment.GetEnvironmentVariable("DEBUG_RESTORE_SETTINGS_TASK");
            if (!string.IsNullOrEmpty(debugRestoreTask) && debugRestoreTask.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase))
            {
                System.Diagnostics.Debugger.Launch();
            }
#endif
            var log = new MSBuildLogger(Log);

            // Log Inputs
            BuildTasksUtility.LogInputParam(log, nameof(ProjectUniqueName), ProjectUniqueName);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSources), RestoreSources);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPath), RestorePackagesPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreRepositoryPath), RestoreRepositoryPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFolders), RestoreFallbackFolders);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreConfigFile), RestoreConfigFile);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSolutionDirectory), RestoreSolutionDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreRootConfigDirectory), RestoreRootConfigDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPathOverride), RestorePackagesPathOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSourcesOverride), RestoreSourcesOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFoldersOverride), RestoreFallbackFoldersOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreProjectStyle), RestoreProjectStyle);
            BuildTasksUtility.LogInputParam(log, nameof(MSBuildStartupDirectory), MSBuildStartupDirectory);


            try
            {
                // Validate inputs
                if (RestoreSourcesOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreSources, ProjectUniqueName, log))
                {
                    // Fail due to invalid source combination
                    return(false);
                }

                if (RestoreFallbackFoldersOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreFallbackFolders, ProjectUniqueName, log))
                {
                    // Fail due to invalid fallback combination
                    return(false);
                }

                // Settings
                // Find the absolute path of nuget.config, this should only be set on the command line. Setting the path in project files
                // is something that could happen, but it is not supported.
                var    absoluteConfigFilePath = GetGlobalAbsolutePath(RestoreConfigFile);
                string restoreDir;
                // To match non-msbuild behavior, we only default the restoreDir for non-PackagesConfig scenarios.
                if (string.IsNullOrEmpty(RestoreRootConfigDirectory))
                {
                    restoreDir = Path.GetDirectoryName(ProjectUniqueName);
                }
                else
                {
                    restoreDir = RestoreRootConfigDirectory;
                }
                var settings = RestoreSettingsUtils.ReadSettings(RestoreSolutionDirectory, restoreDir, absoluteConfigFilePath, _machineWideSettings);
                OutputConfigFilePaths = settings.GetConfigFilePaths().ToArray();

                // PackagesPath
                OutputPackagesPath = RestoreSettingsUtils.GetValue(
                    () => GetGlobalAbsolutePath(RestorePackagesPathOverride),
                    () => string.IsNullOrEmpty(RestorePackagesPath) ? null : UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, RestorePackagesPath),
                    () => SettingsUtility.GetGlobalPackagesFolder(settings));

                OutputRepositoryPath = RestoreSettingsUtils.GetValue(
                    () => GetGlobalAbsolutePath(RestoreRepositoryPathOverride),
                    () => string.IsNullOrEmpty(RestoreRepositoryPath) ? null : UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, RestoreRepositoryPath),
                    () => SettingsUtility.GetRepositoryPath(settings));

                // Sources
                OutputSources = BuildTasksUtility.GetSources(
                    MSBuildStartupDirectory,
                    Path.GetDirectoryName(ProjectUniqueName),
                    RestoreSources,
                    RestoreSourcesOverride,
                    GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectSources"),
                    settings);

                // Fallback folders
                OutputFallbackFolders = BuildTasksUtility.GetFallbackFolders(
                    MSBuildStartupDirectory,
                    Path.GetDirectoryName(ProjectUniqueName),
                    RestoreFallbackFolders, RestoreFallbackFoldersOverride,
                    GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFolders"),
                    GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFoldersExcludes"),
                    settings);
            }
            catch (Exception ex)
            {
                // Log exceptions with error codes if they exist.
                ExceptionUtilities.LogException(ex, log);
                return(false);
            }

            // Log Outputs
            BuildTasksUtility.LogOutputParam(log, nameof(OutputPackagesPath), OutputPackagesPath);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputRepositoryPath), OutputRepositoryPath);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputSources), OutputSources);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputFallbackFolders), OutputFallbackFolders);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputConfigFilePaths), OutputConfigFilePaths);

            return(true);
        }
Esempio n. 7
0
        public static LinkDescriptor GetLinkDescriptor(this DataServiceContext context, object source, string sourceProperty, object target)
        {
            ExceptionUtilities.CheckArgumentNotNull(context, "context");

            return(context.Links.Where(l => l.Source == source && l.Target == target && l.SourceProperty == sourceProperty).SingleOrDefault());
        }
Esempio n. 8
0
 /// <summary>
 /// Adds a ServiceOperationDescriptor to the list of Action/Function Descriptors based on its type
 /// </summary>
 /// <param name="serviceOperationDescriptor">An ActionDescriptor or a FunctionDescriptor to add</param>
 public void Add(ServiceOperationDescriptor serviceOperationDescriptor)
 {
     ExceptionUtilities.CheckArgumentNotNull(serviceOperationDescriptor, "serviceOperationDescriptor");
     this.ServiceOperationDescriptors.Add(serviceOperationDescriptor);
 }
Esempio n. 9
0
        private int DumpILBlock(
            byte[] ilBytes,
            int length,
            StringBuilder sb,
            IReadOnlyList <HandlerSpan> spans,
            int blockOffset,
            int curIndex,
            int spanIndex,
            string indent,
            IReadOnlyDictionary <int, string> markers,
            out int nextSpanIndex)
        {
            int lastSpanIndex = spanIndex - 1;

            while (curIndex < length)
            {
                if (lastSpanIndex > 0 && StartsFilterHandler(spans, lastSpanIndex, curIndex + blockOffset))
                {
                    sb.Append(indent.Substring(0, indent.Length - IndentString.Length));
                    sb.Append("}  // end filter");
                    sb.AppendLine();

                    sb.Append(indent.Substring(0, indent.Length - IndentString.Length));
                    sb.Append("{  // handler");
                    sb.AppendLine();
                }

                if (StartsSpan(spans, spanIndex, curIndex + blockOffset))
                {
                    sb.Append(indent);
                    sb.Append(spans[spanIndex].ToString(this));
                    sb.AppendLine();
                    sb.Append(indent);
                    sb.Append("{");
                    sb.AppendLine();

                    curIndex = DumpILBlock(ilBytes, length, sb, spans, blockOffset, curIndex, spanIndex + 1, indent + IndentString, markers, out spanIndex);

                    sb.Append(indent);
                    sb.Append("}");
                    sb.AppendLine();
                }
                else
                {
                    int    ilOffset = curIndex + blockOffset;
                    string marker;
                    if (markers != null && markers.TryGetValue(ilOffset, out marker))
                    {
                        sb.Append(indent.Substring(0, indent.Length - marker.Length));
                        sb.Append(marker);
                    }
                    else
                    {
                        sb.Append(indent);
                    }

                    sb.AppendFormat("IL_{0:x4}:", ilOffset);

                    OpCode opCode;
                    int    expectedSize;

                    byte op1 = ilBytes[curIndex++];
                    if (op1 == 0xfe && curIndex < length)
                    {
                        byte op2 = ilBytes[curIndex++];
                        opCode       = s_twoByteOpCodes[op2];
                        expectedSize = 2;
                    }
                    else
                    {
                        opCode       = s_oneByteOpCodes[op1];
                        expectedSize = 1;
                    }

                    if (opCode.Size != expectedSize)
                    {
                        sb.AppendLine(string.Format("  <unknown 0x{0}{1:X2}>", expectedSize == 2 ? "fe" : "", op1));
                        continue;
                    }

                    sb.Append("  ");
                    sb.AppendFormat(opCode.OperandType == OperandType.InlineNone ? "{0}" : "{0,-10}", opCode);

                    switch (opCode.OperandType)
                    {
                    case OperandType.InlineField:
                    case OperandType.InlineMethod:
                    case OperandType.InlineTok:
                    case OperandType.InlineType:
                        sb.Append(' ');
                        sb.Append(VisualizeSymbol(ReadUint(ilBytes, ref curIndex)));
                        break;

                    case OperandType.InlineSig:     // signature (calli), not emitted by C#/VB
                        sb.AppendFormat(" 0x{0:x}", ReadUint(ilBytes, ref curIndex));
                        break;

                    case OperandType.InlineString:
                        sb.Append(' ');
                        sb.Append(VisualizeUserString(ReadUint(ilBytes, ref curIndex)));
                        break;

                    case OperandType.InlineNone:
                        break;

                    case OperandType.ShortInlineI:
                        sb.AppendFormat(" {0}", ReadSByte(ilBytes, ref curIndex));
                        break;

                    case OperandType.ShortInlineVar:
                        sb.AppendFormat(" V_{0}", ReadByte(ilBytes, ref curIndex));
                        break;

                    case OperandType.InlineVar:
                        sb.AppendFormat(" V_{0}", ReadUShort(ilBytes, ref curIndex));
                        break;

                    case OperandType.InlineI:
                        sb.AppendFormat(" 0x{0:x}", ReadUint(ilBytes, ref curIndex));
                        break;

                    case OperandType.InlineI8:
                        sb.AppendFormat(" 0x{0:x8}", ReadUlong(ilBytes, ref curIndex));
                        break;

                    case OperandType.ShortInlineR:
                    {
                        var value = ReadSingle(ilBytes, ref curIndex);
                        if (value == 0 && 1 / value < 0)
                        {
                            sb.Append(" -0.0");
                        }
                        else
                        {
                            sb.AppendFormat(" {0}", value.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;

                    case OperandType.InlineR:
                    {
                        var value = ReadDouble(ilBytes, ref curIndex);
                        if (value == 0 && 1 / value < 0)
                        {
                            sb.Append(" -0.0");
                        }
                        else
                        {
                            sb.AppendFormat(" {0}", value.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;

                    case OperandType.ShortInlineBrTarget:
                        sb.AppendFormat(" IL_{0:x4}", ReadSByte(ilBytes, ref curIndex) + curIndex + blockOffset);
                        break;

                    case OperandType.InlineBrTarget:
                        sb.AppendFormat(" IL_{0:x4}", ReadInt(ilBytes, ref curIndex) + curIndex + blockOffset);
                        break;

                    case OperandType.InlineSwitch:
                        int labelCount = ReadInt(ilBytes, ref curIndex);
                        int instrEnd   = curIndex + labelCount * 4;
                        sb.AppendLine("(");
                        for (int i = 0; i < labelCount; i++)
                        {
                            sb.AppendFormat("        IL_{0:x4}", ReadInt(ilBytes, ref curIndex) + instrEnd + blockOffset);
                            sb.AppendLine((i == labelCount - 1) ? ")" : ",");
                        }
                        break;

                    default:
                        throw ExceptionUtilities.UnexpectedValue(opCode.OperandType);
                    }

                    sb.AppendLine();
                }

                if (EndsSpan(spans, lastSpanIndex, curIndex + blockOffset))
                {
                    break;
                }
            }

            nextSpanIndex = spanIndex;
            return(curIndex);
        }
        private void LearnFromAnyNullPatterns(
            int inputSlot,
            TypeSymbol inputType,
            BoundPattern pattern)
        {
            if (inputSlot <= 0)
            {
                return;
            }

            // https://github.com/dotnet/roslyn/issues/35041 We only need to do this when we're rewriting, so we
            // can get information for any nodes in the pattern.
            VisitPatternForRewriting(pattern);

            switch (pattern)
            {
            case BoundConstantPattern cp:
                bool isExplicitNullCheck = cp.Value.ConstantValue == ConstantValue.Null;
                if (isExplicitNullCheck)
                {
                    // Since we're not branching on this null test here, we just infer the top level
                    // nullability.  We'll branch on it later.
                    LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
                }
                break;

            case BoundDeclarationPattern _:
            case BoundDiscardPattern _:
            case BoundITuplePattern _:
            case BoundRelationalPattern _:
                break;     // nothing to learn

            case BoundTypePattern tp:
                if (tp.IsExplicitNotNullTest)
                {
                    LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
                }
                break;

            case BoundRecursivePattern rp:
            {
                if (rp.IsExplicitNotNullTest)
                {
                    LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
                }

                // for positional part: we only learn from tuples (not Deconstruct)
                if (rp.DeconstructMethod is null && !rp.Deconstruction.IsDefault)
                {
                    var elements = inputType.TupleElements;
                    for (int i = 0, n = Math.Min(rp.Deconstruction.Length, elements.IsDefault ? 0 : elements.Length); i < n; i++)
                    {
                        BoundSubpattern item    = rp.Deconstruction[i];
                        FieldSymbol     element = elements[i];
                        LearnFromAnyNullPatterns(GetOrCreateSlot(element, inputSlot), element.Type, item.Pattern);
                    }
                }

                // for property part
                if (!rp.Properties.IsDefault)
                {
                    for (int i = 0, n = rp.Properties.Length; i < n; i++)
                    {
                        BoundSubpattern item   = rp.Properties[i];
                        Symbol          symbol = item.Symbol;
                        if (symbol?.ContainingType.Equals(inputType, TypeCompareKind.AllIgnoreOptions) == true)
                        {
                            LearnFromAnyNullPatterns(GetOrCreateSlot(symbol, inputSlot), symbol.GetTypeOrReturnType().Type, item.Pattern);
                        }
                    }
                }
            }
            break;

            case BoundNegatedPattern p:
                LearnFromAnyNullPatterns(inputSlot, inputType, p.Negated);
                break;

            case BoundBinaryPattern p:
                LearnFromAnyNullPatterns(inputSlot, inputType, p.Left);
                LearnFromAnyNullPatterns(inputSlot, inputType, p.Right);
                break;

            default:
                throw ExceptionUtilities.UnexpectedValue(pattern);
            }
        }
Esempio n. 11
0
            /// <summary>
            /// Visits the payload element
            /// </summary>
            /// <param name="payloadElement">The payload element to visit</param>
            public override void Visit(EntitySetInstance payloadElement)
            {
                ExceptionUtilities.CheckArgumentNotNull(payloadElement, "payloadElement");

                var entitySetAnnotation = payloadElement.Annotations.OfType <EntitySetAnnotation>().SingleOrDefault();

                ExceptionUtilities.CheckObjectNotNull(entitySetAnnotation, "Could not find entity-set annotation on payload element");

                bool expectNextLink   = false;
                var  expectedPageSize = entitySetAnnotation.EntitySet.GetEffectivePageSize();

                if (expectedPageSize.HasValue)
                {
                    // note that the check that the number of elements is less-than-or-equal-to page size happens below
                    expectNextLink = payloadElement.Count == expectedPageSize.Value;
                }

                string message;

                if (this.navigationStack.Count == 0)
                {
                    message = "In root feed";

                    // if the service can tell from the uri that no paging is needed, there will be no next link
                    if (expectNextLink && this.requestUri.Top.HasValue)
                    {
                        expectNextLink &= this.requestUri.Top.Value > expectedPageSize.Value;
                    }
                }
                else
                {
                    message = "In expanded feed";
                }

                using (this.parent.AssertHandler.WithMessage(message))
                {
                    if (expectedPageSize.HasValue)
                    {
                        // verify number of elements. This is also validated based on query expectations in another verifier,
                        // but its cheap and easy to cover here as well to cover our bases.
                        this.parent.AssertHandler.IsTrue(
                            payloadElement.Count <= expectedPageSize.Value,
                            "Number of elements ({0}) exceeds page size ({1}).",
                            payloadElement.Count,
                            expectedPageSize.Value);
                    }

                    if (!expectNextLink)
                    {
                        this.parent.AssertHandler.IsNull(payloadElement.NextLink, "Next link unexpectedly non-null");
                    }
                    else
                    {
                        this.parent.AssertHandler.IsNotNull(payloadElement.NextLink, "Next link unexpectedly null");

                        // only validate the next link if the protocol is implemented based on the expected conventions
                        if (this.payloadOptions.HasFlag(ODataPayloadOptions.UseConventionBasedLinks))
                        {
                            this.GenerateAndCompareNextLink(payloadElement, expectedPageSize.Value);
                        }
                    }

                    this.Recurse(payloadElement);
                }
            }
Esempio n. 12
0
 private PhpSyntaxTree(PhpSourceUnit source)
 {
     _source = source ?? throw ExceptionUtilities.ArgumentNull();
 }
        /// <summary>
        /// Generates the client-side proxy classes then calls the given callback
        /// </summary>
        /// <param name="continuation">The async continuation to report completion on</param>
        /// <param name="serviceRoot">The root uri of the service</param>
        /// <param name="model">The model for the service</param>
        /// <param name="language">The language to generate code in</param>
        /// <param name="onCompletion">The action to invoke with the generated code</param>
        public void GenerateClientCode(IAsyncContinuation continuation, Uri serviceRoot, EntityModelSchema model, IProgrammingLanguageStrategy language, Action <string> onCompletion)
        {
            ExceptionUtilities.CheckArgumentNotNull(continuation, "continuation");
            ExceptionUtilities.CheckArgumentNotNull(serviceRoot, "serviceRoot");
            ExceptionUtilities.CheckArgumentNotNull(model, "model");
            ExceptionUtilities.CheckArgumentNotNull(language, "language");
            ExceptionUtilities.CheckArgumentNotNull(onCompletion, "onCompletion");
            ExceptionUtilities.CheckAllRequiredDependencies(this);

            // because the product code-gen does not produce this overload of the DataServiceContext constructor, we need to add it ourselves
            // namespace <contextNamespace>
            // {
            //   partial class <contextType>
            //   {
            //     public <contextType>(Uri serviceUri, DataServiceProtocolVersion maxProtocolVersion)
            //       : base(serviceUri, maxProtocolVersion)
            //     {
            //     }
            //   }
            // }
            var compileUnit      = new CodeCompileUnit();
            var contextNamespace = compileUnit.AddNamespace(model.EntityTypes.First().NamespaceName);
            var contextType      = contextNamespace.DeclareType(model.EntityContainers.Single().Name);

            contextType.IsPartial = true;

            contextType.AddConstructor()
            .WithArgument(Code.TypeRef <Uri>(), "serviceUri")
            .WithArgument(Code.TypeRef("Microsoft.OData.Client.ODataProtocolVersion"), "maxProtocolVersion")
            .WithBaseConstructorArgument(Code.Variable("serviceUri"))
            .WithBaseConstructorArgument(Code.Variable("maxProtocolVersion"));

            string constructorOverload = language.CreateCodeGenerator().GenerateCodeFromNamespace(contextNamespace);

#if !WIN8
            this.DataServiceBuilder.BeginGenerateClientLayerCode(
                serviceRoot.OriginalString,
                this.DesignVersion,
                this.ClientVersion,
                language.FileExtension,
                result =>
            {
                AsyncHelpers.CatchErrors(
                    continuation,
                    () =>
                {
                    string errorMessage;
                    string clientCode = this.DataServiceBuilder.EndGenerateClientLayerCode(out errorMessage, result);
                    if (errorMessage != null)
                    {
                        throw new TaupoInfrastructureException(errorMessage);
                    }

                    // add the extra constructor overload we generated above
                    clientCode = string.Concat(clientCode, Environment.NewLine, constructorOverload);

                    onCompletion(clientCode);

                    continuation.Continue();
                });
            },
                null);
#else
            var task = this.DataServiceBuilder.GenerateClientLayerCodeAsync(
                new GenerateClientLayerCodeRequest(
                    serviceRoot.OriginalString,
                    this.DesignVersion,
                    this.ClientVersion,
                    language.FileExtension));
            task.Wait();
            var    result       = task.Result;
            string clientCode   = result.GenerateClientLayerCodeResult;
            string errorMessage = result.errorLog;
            if (errorMessage != null)
            {
                throw new TaupoInfrastructureException(errorMessage);
            }

            // add the extra constructor overload we generated above
            clientCode = string.Concat(clientCode, Environment.NewLine, constructorOverload);

            onCompletion(clientCode);

            continuation.Continue();
#endif
        }
Esempio n. 14
0
 public BoundIndirectTypeRef(BoundExpression typeExpression, bool objectTypeInfoSemantic)
 {
     _typeExpression         = typeExpression ?? throw ExceptionUtilities.ArgumentNull();
     _objectTypeInfoSemantic = objectTypeInfoSemantic;
 }
Esempio n. 15
0
        /// <summary>
        /// Bind and return a single type parameter constraint clause along with syntax nodes corresponding to type constraints.
        /// </summary>
        private (TypeParameterConstraintClause, ArrayBuilder <TypeConstraintSyntax>) BindTypeParameterConstraints(TypeParameterSyntax typeParameterSyntax, TypeParameterConstraintClauseSyntax constraintClauseSyntax, bool isForOverride, DiagnosticBag diagnostics)
        {
            var constraints = TypeParameterConstraintKind.None;
            ArrayBuilder <TypeWithAnnotations>  constraintTypes = null;
            ArrayBuilder <TypeConstraintSyntax> syntaxBuilder   = null;
            SeparatedSyntaxList <TypeParameterConstraintSyntax> constraintsSyntax = constraintClauseSyntax.Constraints;

            Debug.Assert(!InExecutableBinder); // Cannot eagerly report diagnostics handled by LazyMissingNonNullTypesContextDiagnosticInfo
            bool hasTypeLikeConstraint           = false;
            bool reportedOverrideWithConstraints = false;

            for (int i = 0, n = constraintsSyntax.Count; i < n; i++)
            {
                var syntax = constraintsSyntax[i];
                switch (syntax.Kind())
                {
                case SyntaxKind.ClassConstraint:
                    hasTypeLikeConstraint = true;

                    if (i != 0)
                    {
                        diagnostics.Add(ErrorCode.ERR_RefValBoundMustBeFirst, syntax.GetFirstToken().GetLocation());

                        if (isForOverride && (constraints & (TypeParameterConstraintKind.ValueType | TypeParameterConstraintKind.ReferenceType)) != 0)
                        {
                            continue;
                        }
                    }

                    var         constraintSyntax = (ClassOrStructConstraintSyntax)syntax;
                    SyntaxToken questionToken    = constraintSyntax.QuestionToken;
                    if (questionToken.IsKind(SyntaxKind.QuestionToken))
                    {
                        constraints |= TypeParameterConstraintKind.NullableReferenceType;

                        if (isForOverride)
                        {
                            reportOverrideWithConstraints(ref reportedOverrideWithConstraints, syntax, diagnostics);
                        }
                        else
                        {
                            LazyMissingNonNullTypesContextDiagnosticInfo.ReportNullableReferenceTypesIfNeeded(AreNullableAnnotationsEnabled(questionToken), questionToken.GetLocation(), diagnostics);
                        }
                    }
                    else if (isForOverride || AreNullableAnnotationsEnabled(constraintSyntax.ClassOrStructKeyword))
                    {
                        constraints |= TypeParameterConstraintKind.NotNullableReferenceType;
                    }
                    else
                    {
                        constraints |= TypeParameterConstraintKind.ReferenceType;
                    }

                    continue;

                case SyntaxKind.StructConstraint:
                    hasTypeLikeConstraint = true;

                    if (i != 0)
                    {
                        diagnostics.Add(ErrorCode.ERR_RefValBoundMustBeFirst, syntax.GetFirstToken().GetLocation());

                        if (isForOverride && (constraints & (TypeParameterConstraintKind.ValueType | TypeParameterConstraintKind.ReferenceType)) != 0)
                        {
                            continue;
                        }
                    }

                    constraints |= TypeParameterConstraintKind.ValueType;
                    continue;

                case SyntaxKind.ConstructorConstraint:
                    if (isForOverride)
                    {
                        reportOverrideWithConstraints(ref reportedOverrideWithConstraints, syntax, diagnostics);
                        continue;
                    }

                    if ((constraints & TypeParameterConstraintKind.ValueType) != 0)
                    {
                        diagnostics.Add(ErrorCode.ERR_NewBoundWithVal, syntax.GetFirstToken().GetLocation());
                    }
                    if ((constraints & TypeParameterConstraintKind.Unmanaged) != 0)
                    {
                        diagnostics.Add(ErrorCode.ERR_NewBoundWithUnmanaged, syntax.GetFirstToken().GetLocation());
                    }

                    if (i != n - 1)
                    {
                        diagnostics.Add(ErrorCode.ERR_NewBoundMustBeLast, syntax.GetFirstToken().GetLocation());
                    }

                    constraints |= TypeParameterConstraintKind.Constructor;
                    continue;

                case SyntaxKind.TypeConstraint:
                    if (isForOverride)
                    {
                        reportOverrideWithConstraints(ref reportedOverrideWithConstraints, syntax, diagnostics);
                    }
                    else
                    {
                        hasTypeLikeConstraint = true;

                        if (constraintTypes == null)
                        {
                            constraintTypes = ArrayBuilder <TypeWithAnnotations> .GetInstance();

                            syntaxBuilder = ArrayBuilder <TypeConstraintSyntax> .GetInstance();
                        }

                        var typeConstraintSyntax = (TypeConstraintSyntax)syntax;
                        var typeSyntax           = typeConstraintSyntax.Type;
                        var typeSyntaxKind       = typeSyntax.Kind();

                        // For pointer types, don't report this error. It is already reported during binding typeSyntax below.
                        switch (typeSyntaxKind)
                        {
                        case SyntaxKind.PredefinedType:
                        case SyntaxKind.PointerType:
                        case SyntaxKind.NullableType:
                            break;

                        default:
                            if (!SyntaxFacts.IsName(typeSyntax.Kind()))
                            {
                                diagnostics.Add(ErrorCode.ERR_BadConstraintType, typeSyntax.GetLocation());
                            }
                            break;
                        }

                        var type = BindTypeOrConstraintKeyword(typeSyntax, diagnostics, out ConstraintContextualKeyword keyword);

                        switch (keyword)
                        {
                        case ConstraintContextualKeyword.Unmanaged:
                            if (i != 0)
                            {
                                diagnostics.Add(ErrorCode.ERR_UnmanagedConstraintMustBeFirst, typeSyntax.GetLocation());
                                continue;
                            }

                            // This should produce diagnostics if the types are missing
                            GetWellKnownType(WellKnownType.System_Runtime_InteropServices_UnmanagedType, diagnostics, typeSyntax);
                            GetSpecialType(SpecialType.System_ValueType, diagnostics, typeSyntax);

                            constraints |= TypeParameterConstraintKind.Unmanaged;
                            continue;

                        case ConstraintContextualKeyword.NotNull:
                            if (i != 0)
                            {
                                diagnostics.Add(ErrorCode.ERR_NotNullConstraintMustBeFirst, typeSyntax.GetLocation());
                            }

                            constraints |= TypeParameterConstraintKind.NotNull;
                            continue;

                        case ConstraintContextualKeyword.None:
                            break;

                        default:
                            throw ExceptionUtilities.UnexpectedValue(keyword);
                        }

                        constraintTypes.Add(type);
                        syntaxBuilder.Add(typeConstraintSyntax);
                    }
                    continue;

                default:
                    throw ExceptionUtilities.UnexpectedValue(syntax.Kind());
                }
            }

            if (!isForOverride && !hasTypeLikeConstraint && !AreNullableAnnotationsEnabled(typeParameterSyntax.Identifier))
            {
                constraints |= TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType;
            }

            Debug.Assert(!isForOverride ||
                         (constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.ValueType)) != (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.ValueType));

            return(TypeParameterConstraintClause.Create(constraints, constraintTypes?.ToImmutableAndFree() ?? ImmutableArray <TypeWithAnnotations> .Empty), syntaxBuilder);
Esempio n. 16
0
        private static bool IsVarianceUnsafe <T>(
            NamedTypeSymbol namedType,
            bool requireOutputSafety,
            bool requireInputSafety,
            Symbol context,
            LocationProvider <T> locationProvider,
            T locationArg,
            BindingDiagnosticBag diagnostics)
            where T : Symbol
        {
            Debug.Assert(requireOutputSafety || requireInputSafety);

            switch (namedType.TypeKind)
            {
            case TypeKind.Class:
            case TypeKind.Struct:
            case TypeKind.Enum:     // Can't be generic, but can be nested in generic.
            case TypeKind.Interface:
            case TypeKind.Delegate:
            case TypeKind.Error:
                break;

            default:
                return(false);
            }

            while ((object)namedType != null)
            {
                for (int i = 0; i < namedType.Arity; i++)
                {
                    TypeParameterSymbol typeParam = namedType.TypeParameters[i];
                    TypeSymbol          typeArg   = namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[i].Type;

                    bool requireOut;
                    bool requireIn;

                    switch (typeParam.Variance)
                    {
                    case VarianceKind.Out:
                        // a) X_i is covariant and A_i is output-unsafe [input-unsafe]
                        requireOut = requireOutputSafety;
                        requireIn  = requireInputSafety;
                        break;

                    case VarianceKind.In:
                        // b) X_i is contravariant and A_i is input-unsafe [output-unsafe]
                        requireOut = requireInputSafety;
                        requireIn  = requireOutputSafety;
                        break;

                    case VarianceKind.None:
                        // c) X_i is invariant and A_i is output-unsafe or input-unsafe
                        requireIn  = true;
                        requireOut = true;
                        break;

                    default:
                        throw ExceptionUtilities.UnexpectedValue(typeParam.Variance);
                    }

                    if (IsVarianceUnsafe(typeArg, requireOut, requireIn, context, locationProvider, locationArg, diagnostics))
                    {
                        return(true);
                    }
                }

                namedType = namedType.ContainingType;
            }

            return(false);
        }
Esempio n. 17
0
        private BoundExpression HoistExpression(
            BoundExpression expr,
            AwaitExpressionSyntax awaitSyntaxOpt,
            int syntaxOffset,
            RefKind refKind,
            ArrayBuilder <BoundExpression> sideEffects,
            ArrayBuilder <StateMachineFieldSymbol> hoistedFields,
            ref bool needsSacrificialEvaluation)
        {
            switch (expr.Kind)
            {
            case BoundKind.ArrayAccess:
            {
                var             array      = (BoundArrayAccess)expr;
                BoundExpression expression = HoistExpression(array.Expression, awaitSyntaxOpt, syntaxOffset, RefKind.None, sideEffects, hoistedFields, ref needsSacrificialEvaluation);
                var             indices    = ArrayBuilder <BoundExpression> .GetInstance();

                foreach (var index in array.Indices)
                {
                    indices.Add(HoistExpression(index, awaitSyntaxOpt, syntaxOffset, RefKind.None, sideEffects, hoistedFields, ref needsSacrificialEvaluation));
                }

                needsSacrificialEvaluation = true;         // need to force array index out of bounds exceptions
                return(array.Update(expression, indices.ToImmutableAndFree(), array.Type));
            }

            case BoundKind.FieldAccess:
            {
                var field = (BoundFieldAccess)expr;
                if (field.FieldSymbol.IsStatic)
                {
                    // the address of a static field, and the value of a readonly static field, is stable
                    if (refKind != RefKind.None || field.FieldSymbol.IsReadOnly)
                    {
                        return(expr);
                    }
                    goto default;
                }

                if (refKind == RefKind.None)
                {
                    goto default;
                }

                var isFieldOfStruct = !field.FieldSymbol.ContainingType.IsReferenceType;

                var receiver = HoistExpression(field.ReceiverOpt, awaitSyntaxOpt, syntaxOffset,
                                               isFieldOfStruct ? refKind : RefKind.None, sideEffects, hoistedFields, ref needsSacrificialEvaluation);
                if (receiver.Kind != BoundKind.ThisReference && !isFieldOfStruct)
                {
                    needsSacrificialEvaluation = true;         // need the null check in field receiver
                }

                return(F.Field(receiver, field.FieldSymbol));
            }

            case BoundKind.ThisReference:
            case BoundKind.BaseReference:
            case BoundKind.DefaultExpression:
                return(expr);

            case BoundKind.Call:
                var call = (BoundCall)expr;
                // NOTE: There are two kinds of 'In' arguments that we may see at this point:
                //       - `RefKindExtensions.StrictIn`     (originally specified with 'In' modifier)
                //       - `RefKind.In`                     (specified with no modifiers and matched an 'In' parameter)
                //
                //       It is allowed to spill ordinary `In` arguments by value if reference-preserving spilling is not possible.
                //       The "strict" ones do not permit implicit copying, so the same situation should result in an error.
                if (refKind != RefKind.None && refKind != RefKind.In)
                {
                    Debug.Assert(call.Method.RefKind != RefKind.None);
                    F.Diagnostics.Add(ErrorCode.ERR_RefReturningCallAndAwait, F.Syntax.Location, call.Method);
                }
                // method call is not referentially transparent, we can only spill the result value.
                refKind = RefKind.None;
                goto default;

            case BoundKind.ConditionalOperator:
                var conditional = (BoundConditionalOperator)expr;
                // NOTE: There are two kinds of 'In' arguments that we may see at this point:
                //       - `RefKindExtensions.StrictIn`     (originally specified with 'In' modifier)
                //       - `RefKind.In`                     (specified with no modifiers and matched an 'In' parameter)
                //
                //       It is allowed to spill ordinary `In` arguments by value if reference-preserving spilling is not possible.
                //       The "strict" ones do not permit implicit copying, so the same situation should result in an error.
                if (refKind != RefKind.None && refKind != RefKind.RefReadOnly)
                {
                    Debug.Assert(conditional.IsRef);
                    F.Diagnostics.Add(ErrorCode.ERR_RefConditionalAndAwait, F.Syntax.Location);
                }
                // conditional expr is not referentially transparent, we can only spill the result value.
                refKind = RefKind.None;
                goto default;

            default:
                if (expr.ConstantValue != null)
                {
                    return(expr);
                }

                if (refKind != RefKind.None)
                {
                    throw ExceptionUtilities.UnexpectedValue(expr.Kind);
                }

                TypeSymbol fieldType = expr.Type;
                StateMachineFieldSymbol hoistedField;
                if (F.Compilation.Options.OptimizationLevel == OptimizationLevel.Debug)
                {
                    const SynthesizedLocalKind kind = SynthesizedLocalKind.AwaitByRefSpill;

                    Debug.Assert(awaitSyntaxOpt != null);

                    int ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(kind, syntaxOffset);
                    var id      = new LocalDebugId(syntaxOffset, ordinal);

                    // Editing await expression is not allowed. Thus all spilled fields will be present in the previous state machine.
                    // However, it may happen that the type changes, in which case we need to allocate a new slot.
                    int slotIndex;
                    if (slotAllocatorOpt == null ||
                        !slotAllocatorOpt.TryGetPreviousHoistedLocalSlotIndex(
                            awaitSyntaxOpt,
                            F.ModuleBuilderOpt.Translate(fieldType, awaitSyntaxOpt, Diagnostics.DiagnosticBag),
                            kind,
                            id,
                            Diagnostics.DiagnosticBag,
                            out slotIndex))
                    {
                        slotIndex = _nextFreeHoistedLocalSlot++;
                    }

                    string fieldName = GeneratedNames.MakeHoistedLocalFieldName(kind, slotIndex);
                    hoistedField = F.StateMachineField(expr.Type, fieldName, new LocalSlotDebugInfo(kind, id), slotIndex);
                }
                else
                {
                    hoistedField = GetOrAllocateReusableHoistedField(fieldType, reused: out _);
                }

                hoistedFields.Add(hoistedField);

                var replacement = F.Field(F.This(), hoistedField);
                sideEffects.Add(F.AssignmentExpression(replacement, expr));
                return(replacement);
            }
        }
        private BoundExpression HoistExpression(
            BoundExpression expr,
            AwaitExpressionSyntax awaitSyntaxOpt,
            int syntaxOffset,
            bool isRef,
            ArrayBuilder <BoundExpression> sideEffects,
            ArrayBuilder <StateMachineFieldSymbol> hoistedFields,
            ref bool needsSacrificialEvaluation)
        {
            switch (expr.Kind)
            {
            case BoundKind.ArrayAccess:
            {
                var             array      = (BoundArrayAccess)expr;
                BoundExpression expression = HoistExpression(array.Expression, awaitSyntaxOpt, syntaxOffset, false, sideEffects, hoistedFields, ref needsSacrificialEvaluation);
                var             indices    = ArrayBuilder <BoundExpression> .GetInstance();

                foreach (var index in array.Indices)
                {
                    indices.Add(HoistExpression(index, awaitSyntaxOpt, syntaxOffset, false, sideEffects, hoistedFields, ref needsSacrificialEvaluation));
                }

                needsSacrificialEvaluation = true;         // need to force array index out of bounds exceptions
                return(array.Update(expression, indices.ToImmutableAndFree(), array.Type));
            }

            case BoundKind.FieldAccess:
            {
                var field = (BoundFieldAccess)expr;
                if (field.FieldSymbol.IsStatic)
                {
                    // the address of a static field, and the value of a readonly static field, is stable
                    if (isRef || field.FieldSymbol.IsReadOnly)
                    {
                        return(expr);
                    }
                    goto default;
                }

                if (!isRef)
                {
                    goto default;
                }

                var isFieldOfStruct = !field.FieldSymbol.ContainingType.IsReferenceType;

                var receiver = HoistExpression(field.ReceiverOpt, awaitSyntaxOpt, syntaxOffset, isFieldOfStruct, sideEffects, hoistedFields, ref needsSacrificialEvaluation);
                if (receiver.Kind != BoundKind.ThisReference && !isFieldOfStruct)
                {
                    needsSacrificialEvaluation = true;         // need the null check in field receiver
                }

                return(F.Field(receiver, field.FieldSymbol));
            }

            case BoundKind.ThisReference:
            case BoundKind.BaseReference:
            case BoundKind.DefaultOperator:
                return(expr);

            default:
                if (expr.ConstantValue != null)
                {
                    return(expr);
                }

                if (isRef)
                {
                    throw ExceptionUtilities.UnexpectedValue(expr.Kind);
                }

                TypeSymbol fieldType = expr.Type;
                StateMachineFieldSymbol hoistedField;
                if (F.Compilation.Options.OptimizationLevel == OptimizationLevel.Debug)
                {
                    const SynthesizedLocalKind kind = SynthesizedLocalKind.AwaitByRefSpill;

                    Debug.Assert(awaitSyntaxOpt != null);

                    int ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(kind, syntaxOffset);
                    var id      = new LocalDebugId(syntaxOffset, ordinal);

                    // Editing await expression is not allowed. Thus all spilled fields will be present in the previous state machine.
                    // However, it may happen that the type changes, in which case we need to allocate a new slot.
                    int slotIndex;
                    if (slotAllocatorOpt == null ||
                        !slotAllocatorOpt.TryGetPreviousHoistedLocalSlotIndex(
                            awaitSyntaxOpt,
                            F.ModuleBuilderOpt.Translate(fieldType, awaitSyntaxOpt, Diagnostics),
                            kind,
                            id,
                            Diagnostics,
                            out slotIndex))
                    {
                        slotIndex = _nextFreeHoistedLocalSlot++;
                    }

                    string fieldName = GeneratedNames.MakeHoistedLocalFieldName(kind, slotIndex);
                    hoistedField = F.StateMachineField(expr.Type, fieldName, new LocalSlotDebugInfo(kind, id), slotIndex);
                }
                else
                {
                    hoistedField = GetOrAllocateReusableHoistedField(fieldType);
                }

                hoistedFields.Add(hoistedField);

                var replacement = F.Field(F.This(), hoistedField);
                sideEffects.Add(F.AssignmentExpression(replacement, expr));
                return(replacement);
            }
        }
Esempio n. 19
0
        public static EntityDescriptor GetEntityDescriptor(this DataServiceContext context, object entity)
        {
            ExceptionUtilities.CheckArgumentNotNull(context, "context");

            return(context.Entities.Where(e => e.Entity == entity).SingleOrDefault());
        }
Esempio n. 20
0
        public static string ToClassificationTypeName(this string taggedTextTag)
        {
            switch (taggedTextTag)
            {
            case TextTags.Keyword:
                return(ClassificationTypeNames.Keyword);

            case TextTags.Class:
                return(ClassificationTypeNames.ClassName);

            case TextTags.Delegate:
                return(ClassificationTypeNames.DelegateName);

            case TextTags.Enum:
                return(ClassificationTypeNames.EnumName);

            case TextTags.Interface:
                return(ClassificationTypeNames.InterfaceName);

            case TextTags.Module:
                return(ClassificationTypeNames.ModuleName);

            case TextTags.Struct:
                return(ClassificationTypeNames.StructName);

            case TextTags.TypeParameter:
                return(ClassificationTypeNames.TypeParameterName);

            case TextTags.Field:
                return(ClassificationTypeNames.FieldName);

            case TextTags.Event:
                return(ClassificationTypeNames.EventName);

            case TextTags.Label:
                return(ClassificationTypeNames.LabelName);

            case TextTags.Local:
                return(ClassificationTypeNames.LocalName);

            case TextTags.Method:
                return(ClassificationTypeNames.MethodName);

            case TextTags.Namespace:
                return(ClassificationTypeNames.NamespaceName);

            case TextTags.Parameter:
                return(ClassificationTypeNames.ParameterName);

            case TextTags.Property:
                return(ClassificationTypeNames.PropertyName);

            case TextTags.ExtensionMethod:
                return(ClassificationTypeNames.ExtensionMethodName);

            case TextTags.EnumMember:
                return(ClassificationTypeNames.EnumMemberName);

            case TextTags.Constant:
                return(ClassificationTypeNames.ConstantName);

            case TextTags.Alias:
            case TextTags.Assembly:
            case TextTags.ErrorType:
            case TextTags.RangeVariable:
                return(ClassificationTypeNames.Identifier);

            case TextTags.NumericLiteral:
                return(ClassificationTypeNames.NumericLiteral);

            case TextTags.StringLiteral:
                return(ClassificationTypeNames.StringLiteral);

            case TextTags.Space:
            case TextTags.LineBreak:
                return(ClassificationTypeNames.WhiteSpace);

            case TextTags.Operator:
                return(ClassificationTypeNames.Operator);

            case TextTags.Punctuation:
                return(ClassificationTypeNames.Punctuation);

            case TextTags.AnonymousTypeIndicator:
            case TextTags.Text:
                return(ClassificationTypeNames.Text);

            default:
                throw ExceptionUtilities.UnexpectedValue(taggedTextTag);
            }
        }
Esempio n. 21
0
            /// <summary>
            /// Decodes a type name.  A type name is a string which is terminated by the end of the string or one of the
            /// delimiters '+', ',', '[', ']'. '+' separates nested classes. '[' and ']'
            /// enclosed generic type arguments.  ',' separates types.
            /// </summary>
            internal AssemblyQualifiedTypeName DecodeTypeName(bool isTypeArgument = false, bool isTypeArgumentWithAssemblyName = false)
            {
                Debug.Assert(!isTypeArgumentWithAssemblyName || isTypeArgument);

                string topLevelType = null;
                ArrayBuilder <string> nestedTypesBuilder = null;

                AssemblyQualifiedTypeName[] typeArguments = null;
                int pointerCount = 0;
                ArrayBuilder <int> arrayRanksBuilder = null;
                string             assemblyName      = null;
                bool decodingTopLevelType            = true;
                bool isGenericTypeName = false;

                var           pooledStrBuilder = PooledStringBuilder.GetInstance();
                StringBuilder typeNameBuilder  = pooledStrBuilder.Builder;

                while (!EndOfInput)
                {
                    int i = _input.IndexOfAny(s_typeNameDelimiters, _offset);
                    if (i >= 0)
                    {
                        char c = _input[i];

                        // Found name, which could be a generic name with arity.
                        // Generic type parameter count, if any, are handled in DecodeGenericName.
                        string decodedString = DecodeGenericName(i);
                        Debug.Assert(decodedString != null);

                        // Type name is generic if the decoded name of the top level type OR any of the outer types of a nested type had the '`' character.
                        isGenericTypeName = isGenericTypeName || decodedString.IndexOf(GenericTypeNameManglingChar) >= 0;
                        typeNameBuilder.Append(decodedString);

                        switch (c)
                        {
                        case '*':
                            if (arrayRanksBuilder != null)
                            {
                                // Error case, array shape must be specified at the end of the type name.
                                // Process as a regular character and continue.
                                typeNameBuilder.Append(c);
                            }
                            else
                            {
                                pointerCount++;
                            }

                            Advance();
                            break;

                        case '+':
                            if (arrayRanksBuilder != null || pointerCount > 0)
                            {
                                // Error case, array shape must be specified at the end of the type name.
                                // Process as a regular character and continue.
                                typeNameBuilder.Append(c);
                            }
                            else
                            {
                                // Type followed by nested type. Handle nested class separator and collect the nested types.
                                HandleDecodedTypeName(typeNameBuilder.ToString(), decodingTopLevelType, ref topLevelType, ref nestedTypesBuilder);
                                typeNameBuilder.Clear();
                                decodingTopLevelType = false;
                            }

                            Advance();
                            break;

                        case '[':
                            // Is type followed by generic type arguments?
                            if (isGenericTypeName && typeArguments == null)
                            {
                                Advance();
                                if (arrayRanksBuilder != null || pointerCount > 0)
                                {
                                    // Error case, array shape must be specified at the end of the type name.
                                    // Process as a regular character and continue.
                                    typeNameBuilder.Append(c);
                                }
                                else
                                {
                                    // Decode type arguments.
                                    typeArguments = DecodeTypeArguments();
                                }
                            }
                            else
                            {
                                // Decode array shape.
                                DecodeArrayShape(typeNameBuilder, ref arrayRanksBuilder);
                            }

                            break;

                        case ']':
                            if (isTypeArgument)
                            {
                                // End of type arguments.  This occurs when the last type argument is a type in the
                                // current assembly.
                                goto ExitDecodeTypeName;
                            }
                            else
                            {
                                // Error case, process as a regular character and continue.
                                typeNameBuilder.Append(c);
                                Advance();
                                break;
                            }

                        case ',':
                            // A comma may separate a type name from its assembly name or a type argument from
                            // another type argument.
                            // If processing non-type argument or a type argument with assembly name,
                            // process the characters after the comma as an assembly name.
                            if (!isTypeArgument || isTypeArgumentWithAssemblyName)
                            {
                                Advance();
                                if (!EndOfInput && Char.IsWhiteSpace(Current))
                                {
                                    Advance();
                                }

                                assemblyName = DecodeAssemblyName(isTypeArgumentWithAssemblyName);
                            }
                            goto ExitDecodeTypeName;

                        default:
                            throw ExceptionUtilities.UnexpectedValue(c);
                        }
                    }
                    else
                    {
                        typeNameBuilder.Append(DecodeGenericName(_input.Length));
                        goto ExitDecodeTypeName;
                    }
                }

ExitDecodeTypeName:
                HandleDecodedTypeName(typeNameBuilder.ToString(), decodingTopLevelType, ref topLevelType, ref nestedTypesBuilder);
                pooledStrBuilder.Free();

                return(new AssemblyQualifiedTypeName(
                           topLevelType,
                           nestedTypesBuilder?.ToArrayAndFree(),
                           typeArguments,
                           pointerCount,
                           arrayRanksBuilder?.ToArrayAndFree(),
                           assemblyName));
            }
Esempio n. 22
0
        bool IDistributionService.Initialize()
        {
            // Start listening to the port if we have remote workers
            if (m_remoteWorkers.Length > 0)
            {
                try
                {
                    m_masterServer.Start(m_buildServicePort);
                }
                catch (Exception ex)
                {
                    Logger.Log.DistributionServiceInitializationError(m_loggingContext, DistributedBuildRole.Master.ToString(), m_buildServicePort, ExceptionUtilities.GetLogEventMessage(ex));
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 23
0
            /// <summary>
            /// Return the side-effect expression corresponding to an evaluation.
            /// </summary>
            protected BoundExpression LowerEvaluation(BoundDagEvaluation evaluation)
            {
                BoundExpression input = _tempAllocator.GetTemp(evaluation.Input);

                switch (evaluation)
                {
                case BoundDagFieldEvaluation f:
                {
                    FieldSymbol     field      = f.Field;
                    var             outputTemp = new BoundDagTemp(f.Syntax, field.Type, f, index: 0);
                    BoundExpression output     = _tempAllocator.GetTemp(outputTemp);
                    BoundExpression access     = _localRewriter.MakeFieldAccess(f.Syntax, input, field, null, LookupResultKind.Viable, field.Type);
                    access.WasCompilerGenerated = true;
                    return(_factory.AssignmentExpression(output, access));
                }

                case BoundDagPropertyEvaluation p:
                {
                    PropertySymbol  property   = p.Property;
                    var             outputTemp = new BoundDagTemp(p.Syntax, property.Type, p, index: 0);
                    BoundExpression output     = _tempAllocator.GetTemp(outputTemp);
                    return(_factory.AssignmentExpression(output, _factory.Property(input, property)));
                }

                case BoundDagDeconstructEvaluation d:
                {
                    MethodSymbol method         = d.DeconstructMethod;
                    var          refKindBuilder = ArrayBuilder <RefKind> .GetInstance();

                    var argBuilder = ArrayBuilder <BoundExpression> .GetInstance();

                    BoundExpression receiver;
                    void addArg(RefKind refKind, BoundExpression expression)
                    {
                        refKindBuilder.Add(refKind);
                        argBuilder.Add(expression);
                    }

                    Debug.Assert(method.Name == WellKnownMemberNames.DeconstructMethodName);
                    int extensionExtra;
                    if (method.IsStatic)
                    {
                        Debug.Assert(method.IsExtensionMethod);
                        receiver = _factory.Type(method.ContainingType);
                        addArg(method.ParameterRefKinds[0], input);
                        extensionExtra = 1;
                    }
                    else
                    {
                        receiver       = input;
                        extensionExtra = 0;
                    }

                    for (int i = extensionExtra; i < method.ParameterCount; i++)
                    {
                        ParameterSymbol parameter = method.Parameters[i];
                        Debug.Assert(parameter.RefKind == RefKind.Out);
                        var outputTemp = new BoundDagTemp(d.Syntax, parameter.Type, d, i - extensionExtra);
                        addArg(RefKind.Out, _tempAllocator.GetTemp(outputTemp));
                    }

                    return(_factory.Call(receiver, method, refKindBuilder.ToImmutableAndFree(), argBuilder.ToImmutableAndFree()));
                }

                case BoundDagTypeEvaluation t:
                {
                    TypeSymbol inputType = input.Type;
                    if (inputType.IsDynamic() || inputType.ContainsTypeParameter())
                    {
                        inputType = _factory.SpecialType(SpecialType.System_Object);
                    }

                    TypeSymbol               type               = t.Type;
                    var                      outputTemp         = new BoundDagTemp(t.Syntax, type, t, index: 0);
                    BoundExpression          output             = _tempAllocator.GetTemp(outputTemp);
                    HashSet <DiagnosticInfo> useSiteDiagnostics = null;
                    Conversion               conversion         = _factory.Compilation.Conversions.ClassifyBuiltInConversion(inputType, output.Type, ref useSiteDiagnostics);
                    _localRewriter._diagnostics.Add(t.Syntax, useSiteDiagnostics);
                    BoundExpression evaluated;
                    if (conversion.Exists)
                    {
                        if (conversion.Kind == ConversionKind.ExplicitNullable &&
                            inputType.GetNullableUnderlyingType().Equals(output.Type, TypeCompareKind.AllIgnoreOptions) &&
                            _localRewriter.TryGetNullableMethod(t.Syntax, inputType, SpecialMember.System_Nullable_T_GetValueOrDefault, out MethodSymbol getValueOrDefault))
                        {
                            // As a special case, since the null test has already been done we can use Nullable<T>.GetValueOrDefault
                            evaluated = _factory.Call(input, getValueOrDefault);
                        }
                        else
                        {
                            evaluated = _factory.Convert(type, input, conversion);
                        }
                    }
                    else
                    {
                        evaluated = _factory.As(input, type);
                    }

                    return(_factory.AssignmentExpression(output, evaluated));
                }

                case BoundDagIndexEvaluation e:
                {
                    // This is an evaluation of an indexed property with a constant int value.
                    // The input type must be ITuple, and the property must be a property of ITuple.
                    Debug.Assert(e.Property.ContainingSymbol.Equals(input.Type));
                    Debug.Assert(e.Property.GetMethod.ParameterCount == 1);
                    Debug.Assert(e.Property.GetMethod.Parameters[0].Type.SpecialType == SpecialType.System_Int32);
                    TypeSymbol      type       = e.Property.GetMethod.ReturnType;
                    var             outputTemp = new BoundDagTemp(e.Syntax, type, e, index: 0);
                    BoundExpression output     = _tempAllocator.GetTemp(outputTemp);
                    return(_factory.AssignmentExpression(output, _factory.Call(input, e.Property.GetMethod, _factory.Literal(e.Index))));
                }

                default:
                    throw ExceptionUtilities.UnexpectedValue(evaluation);
                }
            }
        /// <summary>
        /// Generates the raw test message with mixed encodings defined by the test case, as well as the expected ODataPayloadElement.
        /// </summary>
        /// <param name="testCase">The test case defining the structure and encodings of the batch payload.</param>
        /// <param name="payload">The payload to use for all generated batch operations.</param>
        /// <param name="payloadUri">The URI to use for all generated batch operations.</param>
        /// <param name="isRequest">If true, generates a batch request, otherwise a batch response.</param>
        /// <returns>The test descriptor for this test case/configuration.</returns>
        private BatchReaderMixedEncodingTestDescriptor CreateTestDescriptor(BatchReaderMixedEncodingTestCase testCase, ODataPayloadElement payload, ODataUri payloadUri, bool isRequest)
        {
            ExceptionUtilities.Assert(testCase.BatchEncoding != null, "Batch encoding has not been specified.");

            string batchBoundary    = "batch_" + Guid.NewGuid().ToString();
            string payloadUriString = this.UriConverter.ConvertToString(payloadUri);

            var batchPayload = isRequest ? (ODataPayloadElement) new BatchRequestPayload() : (ODataPayloadElement) new BatchResponsePayload();

            batchPayload.AddAnnotation(new BatchBoundaryAnnotation(batchBoundary));

            var rawMessage = new List <byte>();

            // TODO: Batch reader does not support multi codepoint encodings
            Encoding unsupportedEncoding = AsUnsupportedEncoding(testCase.BatchEncoding);

            foreach (var changeset in testCase.Changesets)
            {
                string   changesetBoundary = "change_" + Guid.NewGuid().ToString();
                Encoding changesetEncoding = changeset.ChangesetEncoding ?? testCase.BatchEncoding;

                // TODO: Batch reader does not support multi codepoint encodings
                unsupportedEncoding = unsupportedEncoding ?? AsUnsupportedEncoding(changesetEncoding);

                string changesetContentType = HttpUtilities.BuildContentType(
                    MimeTypes.MultipartMixed,
                    changeset.ChangesetEncoding == null ? string.Empty : changeset.ChangesetEncoding.WebName,
                    changesetBoundary);

                rawMessage.AddRange(
                    WriteMessagePart(
                        testCase.BatchEncoding,
                        (writer) =>
                {
                    writer.Write("--");
                    writer.WriteLine(batchBoundary);
                    writer.WriteLine(HttpHeaders.ContentType + ": " + changesetContentType);
                    writer.WriteLine();
                }));

                var mimeParts = new List <IMimePart>();
                int contentId = 0;

                foreach (var operation in changeset.Operations)
                {
                    ExceptionUtilities.Assert(operation.PayloadFormat == ODataFormat.Json, "Payload format must be JSON.");
                    string   formatType         = MimeTypes.ApplicationAtomXml + ";type=entry";
                    Encoding payloadEncoding    = operation.OperationEncoding ?? changesetEncoding;
                    string   payloadContentType = HttpUtilities.BuildContentType(
                        formatType,
                        operation.OperationEncoding == null ? string.Empty : operation.OperationEncoding.WebName,
                        string.Empty);

                    string httpStatus = isRequest ? "POST " + payloadUriString + " HTTP/1.1" : "HTTP/1.1 201 Created";

                    rawMessage.AddRange(
                        WriteMessagePart(
                            changesetEncoding,
                            (writer) =>
                    {
                        writer.WriteLine();
                        writer.Write("--");
                        writer.WriteLine(changesetBoundary);
                        writer.WriteLine(HttpHeaders.ContentType + ": application/http");
                        writer.WriteLine(HttpHeaders.ContentTransferEncoding + ": binary");
                        writer.WriteLine(HttpHeaders.ContentId + ": " + (++contentId).ToString());
                        writer.WriteLine();
                        writer.WriteLine(httpStatus);
                        writer.WriteLine(HttpHeaders.ContentType + ": " + payloadContentType);
                        writer.WriteLine();
                    }));

                    IPayloadSerializer payloadSerializer = (IPayloadSerializer) new JsonPayloadSerializer(this.PayloadElementToJsonConverter.ConvertToJson);

                    byte[] payloadBytes = payloadSerializer.SerializeToBinary(payload, payloadEncoding.WebName);
                    rawMessage.AddRange(payloadBytes.Skip(payloadEncoding.GetPreamble().Length));

                    if (isRequest)
                    {
                        var request = this.RequestManager.BuildRequest(payloadUri, HttpVerb.Post, new Dictionary <string, string> {
                            { HttpHeaders.ContentType, payloadContentType }
                        });
                        request.Body = new ODataPayloadBody(payloadBytes, payload);
                        mimeParts.Add(request);
                    }
                    else
                    {
                        var httpResponseData = new HttpResponseData {
                            StatusCode = HttpStatusCode.Created,
                        };
                        httpResponseData.Headers.Add(HttpHeaders.ContentType, payloadContentType);
                        var response = new ODataResponse(httpResponseData)
                        {
                            Body = payloadBytes, RootElement = payload
                        };
                        mimeParts.Add(response);
                    }
                }

                rawMessage.AddRange(
                    WriteMessagePart(
                        changesetEncoding,
                        (writer) =>
                {
                    writer.WriteLine();
                    writer.Write("--");
                    writer.Write(changesetBoundary);
                    writer.WriteLine("--");
                }));

                if (isRequest)
                {
                    ((BatchRequestPayload)batchPayload).Add(BatchPayloadBuilder.RequestChangeset(changesetBoundary, changesetEncoding.WebName, mimeParts.ToArray()));
                }
                else
                {
                    ((BatchResponsePayload)batchPayload).Add(BatchPayloadBuilder.ResponseChangeset(changesetBoundary, changesetEncoding.WebName, mimeParts.ToArray()));
                }
            }

            rawMessage.AddRange(
                WriteMessagePart(
                    testCase.BatchEncoding,
                    (writer) =>
            {
                writer.WriteLine();
                writer.Write("--");
                writer.Write(batchBoundary);
                writer.WriteLine("--");
            }));

            return(new BatchReaderMixedEncodingTestDescriptor(this.PayloadReaderSettings)
            {
                BatchContentTypeHeader = HttpUtilities.BuildContentType(MimeTypes.MultipartMixed, testCase.BatchEncoding.WebName, batchBoundary),
                RawMessage = rawMessage.ToArray(),
                PayloadElement = batchPayload,
                ExpectedException = unsupportedEncoding == null ? null : ODataExpectedExceptions.ODataException("ODataBatchReaderStream_MultiByteEncodingsNotSupported", unsupportedEncoding.WebName)
            });
        }
Esempio n. 25
0
 public ResultTypeBinder(PhpCompilation compilation)
 {
     DeclaringCompilation = compilation ?? throw ExceptionUtilities.ArgumentNull(nameof(compilation));
 }
Esempio n. 26
0
        /// <summary>
        /// Creates and starts a task to deserialize an object
        /// </summary>
        /// <param name="file">This will become the filename</param>
        /// <param name="deserializer">Deserialization function; its get a reader for the file stream, and a function that allows obtaining additional streams if needed</param>
        /// <param name="skipHeader">If enabled, the correlation id is not checked for consistency</param>
        /// <returns>task for deserialized value</returns>
        internal Task <TObject> DeserializeFromFileAsync <TObject>(
            GraphCacheFile file,
            Func <BuildXLReader, Task <TObject> > deserializer,
            bool skipHeader = false)
        {
            var task = Task.Run(
                async() =>
            {
                var objectLabel           = GetFileName(file);
                string path               = GetFullPath(objectLabel);
                FileEnvelope fileEnvelope = GetFileEnvelope(file);

                var result = default(TObject);

                try
                {
                    Stopwatch sw = Stopwatch.StartNew();

                    using (var fileStreamWrapper = m_readStreamProvider.OpenReadStream(path))
                    {
                        var fileStream = fileStreamWrapper.Value;

                        FileEnvelopeId persistedCorrelationId = fileEnvelope.ReadHeader(fileStream);

                        if (!skipHeader)
                        {
                            // We are going to check if all files that are going to be (concurrently) deserialized have matching correlation ids.
                            // The first discovered correlation id is going to be used to check all others.
                            if (m_correlationId == null)
                            {
                                Interlocked.CompareExchange(ref m_correlationId, persistedCorrelationId, null);
                            }

                            FileEnvelope.CheckCorrelationIds(persistedCorrelationId, (FileEnvelopeId)m_correlationId);
                        }

                        var isCompressed = fileStream.ReadByte() == 1;

                        using (Stream readStream = isCompressed ? new BufferedStream(new DeflateStream(fileStream, CompressionMode.Decompress), 64 << 10) : fileStream)
                            using (BuildXLReader reader = new BuildXLReader(m_debug, readStream, leaveOpen: false))
                            {
                                result = await deserializer(reader);
                            }
                    }

                    Tracing.Logger.Log.DeserializedFile(LoggingContext, path, sw.ElapsedMilliseconds);
                    return(result);
                }
                catch (BuildXLException ex)
                {
                    if (ex.InnerException is FileNotFoundException)
                    {
                        // Files might be deleted manually in the EngineCache directory. Log it as verbose.
                        Tracing.Logger.Log.FailedToDeserializeDueToFileNotFound(LoggingContext, path);
                        return(result);
                    }

                    Tracing.Logger.Log.FailedToDeserializePipGraph(LoggingContext, path, ex.LogEventMessage);
                    return(result);
                }
                catch (IOException ex)
                {
                    Tracing.Logger.Log.FailedToDeserializePipGraph(LoggingContext, path, ex.Message);
                    return(result);
                }
                catch (TaskCanceledException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    // There are 2 reasons to be here.
                    //    1. A malformed file can cause ContractException, IndexOutOfRangeException, MemoryException or something else.
                    //    2. We may have a bug.
                    // Since the malformed file will always cause a crash until someone removes the file from the cache, allow BuildXL to recover
                    // by eating the exception. However remember to log it in order to keep track of bugs.
                    ExceptionRootCause rootCause = ExceptionUtilities.AnalyzeExceptionRootCause(ex);
                    BuildXL.Tracing.Logger.Log.UnexpectedCondition(LoggingContext, ex.ToStringDemystified() + Environment.NewLine + rootCause);
                    Tracing.Logger.Log.FailedToDeserializePipGraph(LoggingContext, path, ex.Message);
                    return(result);
                }
            });

            lock (m_deserializationSyncObject)
            {
                m_deserializationTasks.Add(task);
            }

            return(task);
        }
Esempio n. 27
0
        private static void CheckParameterModifiers(
            ParameterSyntax parameter, DiagnosticBag diagnostics)
        {
            var seenThis   = false;
            var seenRef    = false;
            var seenOut    = false;
            var seenParams = false;
            var seenIn     = false;

            foreach (var modifier in parameter.Modifiers)
            {
                switch (modifier.Kind())
                {
                case SyntaxKind.ThisKeyword:
                    if (seenThis)
                    {
                        diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword));
                    }
                    else if (seenOut)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
                    }
                    else if (seenParams)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation());
                    }
                    else
                    {
                        seenThis = true;
                    }
                    break;

                case SyntaxKind.RefKeyword:
                    if (seenRef)
                    {
                        diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
                    }
                    else if (seenParams)
                    {
                        diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
                    }
                    else if (seenOut)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
                    }
                    else if (seenIn)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword));
                    }
                    else
                    {
                        seenRef = true;
                    }
                    break;

                case SyntaxKind.OutKeyword:
                    if (seenOut)
                    {
                        diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
                    }
                    else if (seenThis)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.ThisKeyword));
                    }
                    else if (seenParams)
                    {
                        diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
                    }
                    else if (seenRef)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
                    }
                    else if (seenIn)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword));
                    }
                    else
                    {
                        seenOut = true;
                    }
                    break;

                case SyntaxKind.ParamsKeyword:
                    if (seenParams)
                    {
                        diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword));
                    }
                    else if (seenThis)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation());
                    }
                    else if (seenRef)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
                    }
                    else if (seenIn)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword));
                    }
                    else if (seenOut)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
                    }
                    else
                    {
                        seenParams = true;
                    }
                    break;

                case SyntaxKind.InKeyword:
                    if (seenIn)
                    {
                        diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword));
                    }
                    else if (seenOut)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
                    }
                    else if (seenRef)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
                    }
                    else if (seenParams)
                    {
                        diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword));
                    }
                    else
                    {
                        seenIn = true;
                    }
                    break;

                default:
                    throw ExceptionUtilities.UnexpectedValue(modifier.Kind());
                }
            }
        }
 public AdditionalSyntaxProvider(PhpTokenProvider provider, NodesFactory nodes, Func <QualifiedNameRef, bool, TypeRef> typeRefFactory)
 {
     _provider       = provider ?? throw ExceptionUtilities.ArgumentNull();
     _nodes          = nodes ?? throw ExceptionUtilities.ArgumentNull();
     _typeRefFactory = typeRefFactory ?? throw ExceptionUtilities.ArgumentNull();
 }
Esempio n. 29
0
        private BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node)
        {
            switch (node.Kind)
            {
            case BoundKind.ArrayAccess:
                return(VisitArrayAccess((BoundArrayAccess)node));

            case BoundKind.ArrayCreation:
                return(VisitArrayCreation((BoundArrayCreation)node));

            case BoundKind.ArrayLength:
                return(VisitArrayLength((BoundArrayLength)node));

            case BoundKind.AsOperator:
                return(VisitAsOperator((BoundAsOperator)node));

            case BoundKind.BaseReference:
                return(VisitBaseReference((BoundBaseReference)node));

            case BoundKind.BinaryOperator:
                var binOp = (BoundBinaryOperator)node;
                return(VisitBinaryOperator(binOp.OperatorKind, binOp.MethodOpt, binOp.Type, binOp.Left, binOp.Right));

            case BoundKind.UserDefinedConditionalLogicalOperator:
                var userDefCondLogOp = (BoundUserDefinedConditionalLogicalOperator)node;
                return(VisitBinaryOperator(userDefCondLogOp.OperatorKind, userDefCondLogOp.LogicalOperator, userDefCondLogOp.Type, userDefCondLogOp.Left, userDefCondLogOp.Right));

            case BoundKind.Call:
                return(VisitCall((BoundCall)node));

            case BoundKind.ConditionalOperator:
                return(VisitConditionalOperator((BoundConditionalOperator)node));

            case BoundKind.Conversion:
                return(VisitConversion((BoundConversion)node));

            case BoundKind.PassByCopy:
                return(Visit(((BoundPassByCopy)node).Expression));

            case BoundKind.DelegateCreationExpression:
                return(VisitDelegateCreationExpression((BoundDelegateCreationExpression)node));

            case BoundKind.FieldAccess:
                var fieldAccess = (BoundFieldAccess)node;
                if (fieldAccess.FieldSymbol.IsCapturedFrame)
                {
                    return(Constant(fieldAccess));
                }
                return(VisitFieldAccess(fieldAccess));

            case BoundKind.IsOperator:
                return(VisitIsOperator((BoundIsOperator)node));

            case BoundKind.Lambda:
                return(VisitLambda((BoundLambda)node));

            case BoundKind.NewT:
                return(VisitNewT((BoundNewT)node));

            case BoundKind.NullCoalescingOperator:
                return(VisitNullCoalescingOperator((BoundNullCoalescingOperator)node));

            case BoundKind.ObjectCreationExpression:
                return(VisitObjectCreationExpression((BoundObjectCreationExpression)node));

            case BoundKind.Parameter:
                return(VisitParameter((BoundParameter)node));

            case BoundKind.PointerIndirectionOperator:
                return(VisitPointerIndirectionOperator((BoundPointerIndirectionOperator)node));

            case BoundKind.PointerElementAccess:
                return(VisitPointerElementAccess((BoundPointerElementAccess)node));

            case BoundKind.PropertyAccess:
                return(VisitPropertyAccess((BoundPropertyAccess)node));

            case BoundKind.SizeOfOperator:
                return(VisitSizeOfOperator((BoundSizeOfOperator)node));

            case BoundKind.UnaryOperator:
                return(VisitUnaryOperator((BoundUnaryOperator)node));

            case BoundKind.DefaultExpression:
            case BoundKind.HostObjectMemberReference:
            case BoundKind.Literal:
            case BoundKind.Local:
            case BoundKind.MethodInfo:
            case BoundKind.PreviousSubmissionReference:
            case BoundKind.ThisReference:
            case BoundKind.TypeOfOperator:
                return(Constant(node));

            default:
                throw ExceptionUtilities.UnexpectedValue(node.Kind);
            }
        }
Esempio n. 30
0
 /// <summary>
 /// Converts the given test enum value to the equivalent product enum value
 /// </summary>
 /// <param name="version">The value to convert</param>
 /// <returns>The converted value</returns>
 public static DC.ODataProtocolVersion ToProductEnum(this DataServiceProtocolVersion version)
 {
     ExceptionUtilities.Assert(version != DataServiceProtocolVersion.Unspecified, "Cannot convert unspecified version value");
     ExceptionUtilities.Assert(version != DataServiceProtocolVersion.LatestVersionPlusOne, "Cannot convert latest +1 version value");
     return(ExtensionMethods.ConvertEnum <DataServiceProtocolVersion, DC.ODataProtocolVersion>(version));
 }