public static bool TryGetCompileTimeString( this ExpressionSyntax expression, SemanticModelDecorator semanticModel, [NotNullWhen(true)] out string?result ) { if (expression is null) { throw new ArgumentNullException(nameof(expression)); } if (semanticModel is null) { throw new ArgumentNullException(nameof(semanticModel)); } if (expression is LiteralExpressionSyntax literal) { result = literal.Token.ValueText; return(true); } var constant = semanticModel.GetConstantValue(expression); if (constant.HasValue) { result = constant.Value !.ToString() !; return(true); } result = null; return(false); }
private void CheckForAllowedSyntaxForConstantBinding( ) { var child = _constantClause.ChildNodes().FirstOrDefault(); if (child == null) { throw new DpdtException( DpdtExceptionTypeEnum.InternalError, $"Unknown error during validation a target in 'constant' binding." ); } var cconstant = _semanticModel.GetConstantValue(child); if (cconstant.HasValue) { //it's a true constant, keep going! return; } var ilsymbol = _semanticModel.GetSymbolInfo(child).Symbol; if (ilsymbol is null) { throw new DpdtException( DpdtExceptionTypeEnum.InternalError, $"Unknown error during validation a target in 'constant' binding." ); } if (ilsymbol.Kind != SymbolKind.Field) { throw new DpdtException( DpdtExceptionTypeEnum.InternalError, $"Unsupported type of 'constant' binding. Allowed compile-time constants, readonly fields and readonly static fields only." ); } var filsymbol = ilsymbol as IFieldSymbol; if (filsymbol is null) { throw new DpdtException( DpdtExceptionTypeEnum.InternalError, $"Unknown error during validation a target in 'constant' binding." ); } if (!filsymbol.IsReadOnly) { throw new DpdtException( DpdtExceptionTypeEnum.InternalError, $"Unsupported type of 'constant' binding. Allowed compile-time constants, readonly fields and readonly static fields only." ); } }