private static void DetectDuplicateNames(SemanticModel semanticModel, IDiagnosticWriter diagnosticWriter, ImmutableDictionary <ResourceMetadata, ScopeHelper.ScopeData> resourceScopeData, ImmutableDictionary <ModuleSymbol, ScopeHelper.ScopeData> moduleScopeData) { // This method only checks, if in one deployment we do not have 2 or more resources with this same name in one deployment to avoid template validation error // This will not check resource constraints such as necessity of having unique virtual network names within resource group var duplicateResources = GetResourceDefinitions(semanticModel, resourceScopeData) .GroupBy(x => x, ResourceDefinition.EqualityComparer) .Where(group => group.Count() > 1); foreach (var duplicatedResourceGroup in duplicateResources) { var duplicatedResourceNames = duplicatedResourceGroup.Select(x => x.ResourceName).ToArray(); foreach (var duplicatedResource in duplicatedResourceGroup) { diagnosticWriter.Write(duplicatedResource.ResourceNamePropertyValue, x => x.ResourceMultipleDeclarations(duplicatedResourceNames)); } } var duplicateModules = GetModuleDefinitions(semanticModel, moduleScopeData) .GroupBy(x => x, ModuleDefinition.EqualityComparer) .Where(group => group.Count() > 1); foreach (var duplicatedModuleGroup in duplicateModules) { var duplicatedModuleNames = duplicatedModuleGroup.Select(x => x.ModuleName).ToArray(); foreach (var duplicatedModule in duplicatedModuleGroup) { diagnosticWriter.Write(duplicatedModule.ModulePropertyNameValue, x => x.ModuleMultipleDeclarations(duplicatedModuleNames)); } } }
public override void VisitIntegerLiteralSyntax(IntegerLiteralSyntax syntax) { // syntax.Value is always positive and can't be greater than the greatest 64 bit integer if (syntax.Value > long.MaxValue) { diagnosticWriter.Write(DiagnosticBuilder.ForPosition(syntax).InvalidInteger()); } base.VisitIntegerLiteralSyntax(syntax); }
public static ImmutableDictionary <ModuleSymbol, ScopeHelper.ScopeData> GetSupportedScopeInfo(SemanticModel semanticModel, IDiagnosticWriter diagnosticWriter) { var moduleScopeData = new Dictionary <ModuleSymbol, ScopeHelper.ScopeData>(); foreach (var moduleSymbol in semanticModel.Root.ModuleDeclarations) { var scopeValue = moduleSymbol.SafeGetBodyPropertyValue(LanguageConstants.ResourceScopePropertyName); if (scopeValue == null) { // no scope provided - assume the parent scope moduleScopeData[moduleSymbol] = new ScopeHelper.ScopeData { RequestedScope = semanticModel.TargetScope }; continue; } var scopeType = semanticModel.GetTypeInfo(scopeValue); var scopeData = ScopeHelper.TryGetScopeData(semanticModel.TargetScope, scopeType); if (scopeData != null) { moduleScopeData[moduleSymbol] = scopeData; continue; } switch (semanticModel.TargetScope) { case ResourceScopeType.TenantScope: diagnosticWriter.Write(scopeValue, x => x.InvalidModuleScopeForTenantScope()); break; case ResourceScopeType.ManagementGroupScope: diagnosticWriter.Write(scopeValue, x => x.InvalidModuleScopeForManagementScope()); break; case ResourceScopeType.SubscriptionScope: diagnosticWriter.Write(scopeValue, x => x.InvalidModuleScopeForSubscriptionScope()); break; case ResourceScopeType.ResourceGroupScope: diagnosticWriter.Write(scopeValue, x => x.InvalidModuleScopeForResourceGroup()); break; default: throw new InvalidOperationException($"Unrecognized target scope {semanticModel.TargetScope}"); } } return(moduleScopeData.ToImmutableDictionary()); }
public static ImmutableDictionary <ResourceSymbol, ResourceSymbol?> GetResoureScopeInfo(SemanticModel semanticModel, IDiagnosticWriter diagnosticWriter) { var scopeInfo = new Dictionary <ResourceSymbol, ResourceSymbol?>(); foreach (var resourceSymbol in semanticModel.Root.ResourceDeclarations) { var scopeValue = resourceSymbol.SafeGetBodyPropertyValue(LanguageConstants.ResourceScopePropertyName); if (scopeValue is null) { scopeInfo[resourceSymbol] = null; continue; } var scopeSymbol = semanticModel.GetSymbolInfo(scopeValue); if (scopeSymbol is not ResourceSymbol targetResourceSymbol) { scopeInfo[resourceSymbol] = null; diagnosticWriter.Write(scopeValue, x => x.InvalidExtensionResourceScope()); continue; } scopeInfo[resourceSymbol] = targetResourceSymbol; } return(scopeInfo.ToImmutableDictionary()); }
public static void WriteMultiple(this IDiagnosticWriter diagnosticWriter, IEnumerable <Diagnostic> diagnostics) { foreach (var diagnostic in diagnostics) { diagnosticWriter.Write(diagnostic); } }
private static TypeSymbol NarrowTypeInternal(ITypeManager typeManager, SyntaxBase expression, TypeSymbol targetType, IDiagnosticWriter diagnosticWriter, TypeMismatchErrorFactory typeMismatchErrorFactory, bool skipConstantCheck, bool skipTypeErrors) { if (targetType is ResourceType targetResourceType) { // When assigning a resource, we're really assigning the value of the resource body. var narrowedBody = NarrowTypeInternal(typeManager, expression, targetResourceType.Body.Type, diagnosticWriter, typeMismatchErrorFactory, skipConstantCheck, skipTypeErrors); return(new ResourceType(targetResourceType.TypeReference, targetResourceType.ValidParentScopes, narrowedBody)); } if (targetType is ModuleType targetModuleType) { var narrowedBody = NarrowTypeInternal(typeManager, expression, targetModuleType.Body.Type, diagnosticWriter, typeMismatchErrorFactory, skipConstantCheck, skipTypeErrors); return(new ModuleType(targetModuleType.Name, targetModuleType.ValidParentScopes, narrowedBody)); } // TODO: The type of this expression and all subexpressions should be cached var expressionType = typeManager.GetTypeInfo(expression); // since we dynamically checked type, we need to collect the errors but only if the caller wants them if (skipTypeErrors == false && expressionType is ErrorType) { diagnosticWriter.WriteMultiple(expressionType.GetDiagnostics()); return(targetType); } // basic assignability check if (AreTypesAssignable(expressionType, targetType) == false) { // fundamentally different types - cannot assign diagnosticWriter.Write(typeMismatchErrorFactory(targetType, expressionType, expression)); return(targetType); } // object assignability check if (expression is ObjectSyntax objectValue) { switch (targetType) { case ObjectType targetObjectType: return(NarrowObjectType(typeManager, objectValue, targetObjectType, diagnosticWriter, skipConstantCheck)); case DiscriminatedObjectType targetDiscriminated: return(NarrowDiscriminatedObjectType(typeManager, objectValue, targetDiscriminated, diagnosticWriter, skipConstantCheck)); } } // if-condition assignability check if (expression is IfConditionSyntax { Body : ObjectSyntax body })
public static void DetectIncorrectlyFormattedNames(SemanticModel semanticModel, IDiagnosticWriter diagnosticWriter) { foreach (var resource in semanticModel.Root.GetAllResourceDeclarations()) { if (semanticModel.GetTypeInfo(resource.DeclaringSyntax) is not ResourceType resourceType) { continue; } var resourceName = resource.SafeGetBodyPropertyValue(LanguageConstants.ResourceNamePropertyName); if (resourceName is not StringSyntax resourceNameString) { // not easy to do analysis if it's not a string! continue; } var ancestors = semanticModel.ResourceAncestors.GetAncestors(resource); if (ancestors.Any()) { // try to detect cases where someone has applied top-level resource declaration naming to a nested/parent resource // e.g. '{parent.name}/child' or 'parent/child' if (resourceNameString.SegmentValues.Any(v => v.IndexOf('/') > -1)) { diagnosticWriter.Write(resourceName, x => x.ChildResourceNameContainsQualifiers()); } } else { if (resourceNameString.TryGetLiteralValue() is {} typeString) { // try to detect cases where someone has applied nested/parent resource declaration naming to a top-level resource - e.g. 'child'. // this unfortunately limits us to only validating uninterpolated strings, as we can't do analysis on the number of '/' characters // being pulled in from variables. var slashCount = typeString.Count(x => x == '/'); var expectedSlashCount = resourceType.TypeReference.Types.Length - 1; if (slashCount != expectedSlashCount) { diagnosticWriter.Write(resourceName, x => x.TopLevelChildResourceNameMissingQualifiers(expectedSlashCount)); } } } } }
private static TypeSymbol LoadTextContentTypeBuilder(IBinder binder, IFileResolver fileResolver, IDiagnosticWriter diagnostics, ImmutableArray <FunctionArgumentSyntax> arguments, ImmutableArray <TypeSymbol> argumentTypes) { if (argumentTypes[0] is not StringLiteralType filePathType) { diagnostics.Write(DiagnosticBuilder.ForPosition(arguments[0]).CompileTimeConstantRequired()); return(LanguageConstants.String); } var filePathValue = filePathType.RawStringValue; var fileUri = GetFileUriWithDiagnostics(binder, fileResolver, diagnostics, filePathValue, arguments[0]); if (fileUri is null) { return(LanguageConstants.String); } var fileEncoding = Encoding.UTF8; if (argumentTypes.Length > 1) { if (argumentTypes[1] is not StringLiteralType encodingType) { diagnostics.Write(DiagnosticBuilder.ForPosition(arguments[1]).CompileTimeConstantRequired()); return(LanguageConstants.String); } fileEncoding = LanguageConstants.SupportedEncodings.First(x => string.Equals(x.name, encodingType.RawStringValue, LanguageConstants.IdentifierComparison)).encoding; } if (!fileResolver.TryRead(fileUri, out var fileContent, out var fileReadFailureBuilder, fileEncoding, LanguageConstants.MaxLiteralCharacterLimit, out var detectedEncoding)) { diagnostics.Write(fileReadFailureBuilder.Invoke(DiagnosticBuilder.ForPosition(arguments[0]))); return(LanguageConstants.String); } if (arguments.Length > 1 && fileEncoding != detectedEncoding) { diagnostics.Write(DiagnosticBuilder.ForPosition(arguments[1]).FileEncodingMismatch(detectedEncoding.WebName)); } return(new StringLiteralType(fileContent)); }
private static TypeSymbol LoadContentAsBase64TypeBuilder(IBinder binder, IFileResolver fileResolver, IDiagnosticWriter diagnostics, ImmutableArray <FunctionArgumentSyntax> arguments, ImmutableArray <TypeSymbol> argumentTypes) { if (argumentTypes[0] is not StringLiteralType filePathType) { diagnostics.Write(DiagnosticBuilder.ForPosition(arguments[0]).CompileTimeConstantRequired()); return(LanguageConstants.String); } var filePathValue = filePathType.RawStringValue; var fileUri = GetFileUriWithDiagnostics(binder, fileResolver, diagnostics, filePathValue, arguments[0]); if (fileUri is null) { return(LanguageConstants.String); } if (!fileResolver.TryReadAsBase64(fileUri, out var fileContent, out var fileReadFailureBuilder, LanguageConstants.MaxLiteralCharacterLimit)) { diagnostics.Write(fileReadFailureBuilder.Invoke(DiagnosticBuilder.ForPosition(arguments[0]))); return(LanguageConstants.String); } return(new StringLiteralType(binder.FileSymbol.FileUri.MakeRelativeUri(fileUri).ToString(), fileContent)); }
private static Uri?GetFileUriWithDiagnostics(IBinder binder, IFileResolver fileResolver, IDiagnosticWriter diagnostics, string filePath, SyntaxBase filePathArgument) { if (!LocalModuleReference.Validate(filePath, out var validateFilePathFailureBuilder)) { diagnostics.Write(validateFilePathFailureBuilder.Invoke(DiagnosticBuilder.ForPosition(filePathArgument))); return(null); } var fileUri = fileResolver.TryResolveFilePath(binder.FileSymbol.FileUri, filePath); if (fileUri is null) { diagnostics.Write(DiagnosticBuilder.ForPosition(filePathArgument).FilePathCouldNotBeResolved(filePath, binder.FileSymbol.FileUri.LocalPath)); return(null); } if (!fileUri.IsFile) { diagnostics.Write(DiagnosticBuilder.ForPosition(filePathArgument).UnableToLoadNonFileUri(fileUri)); return(null); } return(fileUri); }
public void Validate(DecoratorSyntax decoratorSyntax, TypeSymbol targetType, ITypeManager typeManager, IBinder binder, IDiagnosticWriter diagnosticWriter) { if (targetType is ErrorType) { return; } if (!this.CanAttachTo(targetType)) { diagnosticWriter.Write(DiagnosticBuilder.ForPosition(decoratorSyntax).CannotAttachDecoratorToTarget(this.Overload.Name, attachableType, targetType)); } // Invoke custom validator if provided. this.validator?.Invoke(this.Overload.Name, decoratorSyntax, targetType, typeManager, binder, diagnosticWriter); }
public void Validate(DecoratorSyntax decoratorSyntax, TypeSymbol targetType, ITypeManager typeManager, IDiagnosticWriter diagnosticWriter) { if (targetType is ErrorType) { return; } if (this.validator != null) { this.validator.Invoke(this.Overload.Name, decoratorSyntax, targetType, typeManager, diagnosticWriter); return; } // No custom validator provided. Just validate the target type. if (!this.CanAttachTo(targetType)) { diagnosticWriter.Write(DiagnosticBuilder.ForPosition(decoratorSyntax).CannotAttacheDecoratorToTarget(this.Overload.Name, attachableType, targetType)); } }
private static TypeSymbol NarrowObjectType(ITypeManager typeManager, ObjectSyntax expression, ObjectType targetType, IDiagnosticWriter diagnosticWriter, bool skipConstantCheck) { // TODO: Short-circuit on any object to avoid unnecessary processing? // TODO: Consider doing the schema check even if there are parse errors // if we have parse errors, there's no point to check assignability // we should not return the parse errors however because they will get double collected if (expression.HasParseErrors()) { return(targetType); } var namedPropertyMap = expression.ToNamedPropertyDictionary(); var missingRequiredProperties = targetType.Properties.Values .Where(p => p.Flags.HasFlag(TypePropertyFlags.Required) && !namedPropertyMap.ContainsKey(p.Name)) .Select(p => p.Name) .OrderBy(p => p); if (missingRequiredProperties.Any()) { IPositionable positionable = expression; string blockName = "object"; var parent = typeManager.GetParent(expression); if (parent is ObjectPropertySyntax objectPropertyParent) { positionable = objectPropertyParent.Key; blockName = "object"; } else if (parent is INamedDeclarationSyntax declarationParent) { positionable = declarationParent.Name; blockName = declarationParent.Keyword.Text; } diagnosticWriter.Write(DiagnosticBuilder.ForPosition(positionable).MissingRequiredProperties(ShouldWarn(targetType), missingRequiredProperties, blockName)); } var narrowedProperties = new List <TypeProperty>(); foreach (var declaredProperty in targetType.Properties.Values) { if (namedPropertyMap.TryGetValue(declaredProperty.Name, out var declaredPropertySyntax)) { bool skipConstantCheckForProperty = skipConstantCheck; // is the property marked as requiring compile-time constants and has the parent already validated this? if (skipConstantCheck == false && declaredProperty.Flags.HasFlag(TypePropertyFlags.Constant)) { // validate that values are compile-time constants GetCompileTimeConstantViolation(declaredPropertySyntax.Value, diagnosticWriter); // disable compile-time constant validation for children skipConstantCheckForProperty = true; } if (declaredProperty.Flags.HasFlag(TypePropertyFlags.ReadOnly)) { // the declared property is read-only // value cannot be assigned to a read-only property diagnosticWriter.Write(DiagnosticBuilder.ForPosition(declaredPropertySyntax.Key).CannotAssignToReadOnlyProperty(ShouldWarn(targetType), declaredProperty.Name)); narrowedProperties.Add(new TypeProperty(declaredProperty.Name, declaredProperty.TypeReference.Type, declaredProperty.Flags)); continue; } // declared property is specified in the value object // validate type var narrowedType = NarrowTypeInternal( typeManager, declaredPropertySyntax.Value, declaredProperty.TypeReference.Type, diagnosticWriter, GetPropertyMismatchErrorFactory(ShouldWarn(targetType), declaredProperty.Name), skipConstantCheckForProperty, skipTypeErrors: true); narrowedProperties.Add(new TypeProperty(declaredProperty.Name, narrowedType, declaredProperty.Flags)); } else { narrowedProperties.Add(declaredProperty); } } // find properties that are specified on in the expression object but not declared in the schema var extraProperties = expression.Properties .Where(p => !(p.TryGetKeyText() is string keyName) || !targetType.Properties.ContainsKey(keyName)); if (targetType.AdditionalPropertiesType == null) { bool shouldWarn = ShouldWarn(targetType); var validUnspecifiedProperties = targetType.Properties.Values .Where(p => !p.Flags.HasFlag(TypePropertyFlags.ReadOnly) && !namedPropertyMap.ContainsKey(p.Name)) .Select(p => p.Name) .OrderBy(x => x); // extra properties are not allowed by the type foreach (var extraProperty in extraProperties) { Diagnostic error; var builder = DiagnosticBuilder.ForPosition(extraProperty.Key); if (extraProperty.TryGetKeyText() is string keyName) { error = validUnspecifiedProperties.Any() switch { true => SpellChecker.GetSpellingSuggestion(keyName, validUnspecifiedProperties) switch { string suggestedKeyName when suggestedKeyName != null => builder.DisallowedPropertyWithSuggestion(shouldWarn, keyName, targetType, suggestedKeyName), _ => builder.DisallowedPropertyWithPermissibleProperties(shouldWarn, keyName, targetType, validUnspecifiedProperties) },
private static TypeSymbol NarrowDiscriminatedObjectType(ITypeManager typeManager, ObjectSyntax expression, DiscriminatedObjectType targetType, IDiagnosticWriter diagnosticWriter, bool skipConstantCheck) { // if we have parse errors, there's no point to check assignability // we should not return the parse errors however because they will get double collected if (expression.HasParseErrors()) { return(LanguageConstants.Any); } var discriminatorProperty = expression.Properties.FirstOrDefault(x => LanguageConstants.IdentifierComparer.Equals(x.TryGetKeyText(), targetType.DiscriminatorKey)); if (discriminatorProperty == null) { // object doesn't contain the discriminator field diagnosticWriter.Write(DiagnosticBuilder.ForPosition(expression).MissingRequiredProperty(ShouldWarn(targetType), targetType.DiscriminatorKey, targetType.DiscriminatorKeysUnionType)); var propertyKeys = expression.Properties .Select(x => x.TryGetKeyText()) .Where(key => !string.IsNullOrEmpty(key)) .Select(key => key !); // do a reverse lookup to check if there's any misspelled discriminator key var misspelledDiscriminatorKey = SpellChecker.GetSpellingSuggestion(targetType.DiscriminatorKey, propertyKeys); if (misspelledDiscriminatorKey != null) { diagnosticWriter.Write(DiagnosticBuilder.ForPosition(expression).DisallowedPropertyWithSuggestion(ShouldWarn(targetType), misspelledDiscriminatorKey, targetType.DiscriminatorKeysUnionType, targetType.DiscriminatorKey)); } return(LanguageConstants.Any); } // At some point in the future we may want to relax the expectation of a string literal key, and allow a generic string. // In this case, the best we can do is validate against the union of all the settable properties. // Let's not do this just yet, and see if a use-case arises. var discriminatorType = typeManager.GetTypeInfo(discriminatorProperty.Value); if (!(discriminatorType is StringLiteralType stringLiteralDiscriminator)) { diagnosticWriter.Write(DiagnosticBuilder.ForPosition(expression).PropertyTypeMismatch(ShouldWarn(targetType), targetType.DiscriminatorKey, targetType.DiscriminatorKeysUnionType, discriminatorType)); return(LanguageConstants.Any); } if (!targetType.UnionMembersByKey.TryGetValue(stringLiteralDiscriminator.Name, out var selectedObjectReference)) { // no matches var discriminatorCandidates = targetType.UnionMembersByKey.Keys.OrderBy(x => x); string?suggestedDiscriminator = SpellChecker.GetSpellingSuggestion(stringLiteralDiscriminator.Name, discriminatorCandidates); var builder = DiagnosticBuilder.ForPosition(discriminatorProperty.Value); bool shouldWarn = ShouldWarn(targetType); diagnosticWriter.Write(suggestedDiscriminator != null ? builder.PropertyStringLiteralMismatchWithSuggestion(shouldWarn, targetType.DiscriminatorKey, targetType.DiscriminatorKeysUnionType, stringLiteralDiscriminator.Name, suggestedDiscriminator) : builder.PropertyTypeMismatch(shouldWarn, targetType.DiscriminatorKey, targetType.DiscriminatorKeysUnionType, discriminatorType)); return(LanguageConstants.Any); } if (!(selectedObjectReference.Type is ObjectType selectedObjectType)) { throw new InvalidOperationException($"Discriminated type {targetType.Name} contains non-object member"); } // we have a match! return(NarrowObjectType(typeManager, expression, selectedObjectType, diagnosticWriter, skipConstantCheck)); }
public static void Write(this IDiagnosticWriter diagnosticWriter, IPositionable positionable, DiagnosticBuilder.DiagnosticBuilderDelegate buildDiagnosticFunc) => diagnosticWriter.Write(buildDiagnosticFunc(DiagnosticBuilder.ForPosition(positionable)));