diff --git a/Jint/AssemblyInfoExtras.cs b/Jint/AssemblyInfoExtras.cs index 7359aca575..d9ed0076d7 100644 --- a/Jint/AssemblyInfoExtras.cs +++ b/Jint/AssemblyInfoExtras.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Jint.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100bf2553c9f214cb21f1f64ed62cadad8fe4f2fa11322a5dfa1d650743145c6085aba05b145b29867af656e0bb9bfd32f5d0deb1668263a38233e7e8e5bad1a3c6edd3f2ec6c512668b4aa797283101444628650949641b4f7cb16707efba542bb754afe87ce956f3a5d43f450d14364eb9571cbf213d1061852fb9dd47a6c05c4")] [assembly: InternalsVisibleTo("Jint.Tests.Test262, PublicKey=0024000004800000940000000602000000240000525341310004000001000100bf2553c9f214cb21f1f64ed62cadad8fe4f2fa11322a5dfa1d650743145c6085aba05b145b29867af656e0bb9bfd32f5d0deb1668263a38233e7e8e5bad1a3c6edd3f2ec6c512668b4aa797283101444628650949641b4f7cb16707efba542bb754afe87ce956f3a5d43f450d14364eb9571cbf213d1061852fb9dd47a6c05c4")] diff --git a/Jint/Collections/DictionarySlim.cs b/Jint/Collections/DictionarySlim.cs index 754772795b..e4547720d0 100644 --- a/Jint/Collections/DictionarySlim.cs +++ b/Jint/Collections/DictionarySlim.cs @@ -1,4 +1,6 @@ -// Licensed to the .NET Foundation under one or more agreements. +#nullable disable + +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. diff --git a/Jint/Collections/HybridDictionary.cs b/Jint/Collections/HybridDictionary.cs index d4b3a4efea..05ab7a4bff 100644 --- a/Jint/Collections/HybridDictionary.cs +++ b/Jint/Collections/HybridDictionary.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Collections; using System.Runtime.CompilerServices; diff --git a/Jint/Collections/ListDictionary.cs b/Jint/Collections/ListDictionary.cs index 9f2a0eb309..2a301fb7ee 100644 --- a/Jint/Collections/ListDictionary.cs +++ b/Jint/Collections/ListDictionary.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Collections; using System.Runtime.CompilerServices; using Jint.Runtime; diff --git a/Jint/Collections/PropertyDictionary.cs b/Jint/Collections/PropertyDictionary.cs index d9b1517073..daea0f27fa 100644 --- a/Jint/Collections/PropertyDictionary.cs +++ b/Jint/Collections/PropertyDictionary.cs @@ -12,4 +12,4 @@ public PropertyDictionary(int capacity, bool checkExistingKeys) : base(capacity, { } } -} \ No newline at end of file +} diff --git a/Jint/Collections/RefStack.cs b/Jint/Collections/RefStack.cs index 488ce8e363..5827448ed6 100644 --- a/Jint/Collections/RefStack.cs +++ b/Jint/Collections/RefStack.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; diff --git a/Jint/Collections/StringDictionarySlim.cs b/Jint/Collections/StringDictionarySlim.cs index f27e927dd7..5621856171 100644 --- a/Jint/Collections/StringDictionarySlim.cs +++ b/Jint/Collections/StringDictionarySlim.cs @@ -1,4 +1,6 @@ -// Licensed to the .NET Foundation under one or more agreements. +#nullable disable + +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. diff --git a/Jint/Collections/SymbolDictionary.cs b/Jint/Collections/SymbolDictionary.cs index 1756535edf..182cf9ba2e 100644 --- a/Jint/Collections/SymbolDictionary.cs +++ b/Jint/Collections/SymbolDictionary.cs @@ -13,4 +13,4 @@ public SymbolDictionary(int capacity) : base(capacity) { } } -} \ No newline at end of file +} diff --git a/Jint/Constraints/CancellationConstraint.cs b/Jint/Constraints/CancellationConstraint.cs index f7c44ea6d4..ed623019dc 100644 --- a/Jint/Constraints/CancellationConstraint.cs +++ b/Jint/Constraints/CancellationConstraint.cs @@ -1,4 +1,4 @@ -using Jint.Runtime; +using Jint.Runtime; using System.Threading; namespace Jint.Constraints diff --git a/Jint/Constraints/ConstraintsOptionsExtensions.cs b/Jint/Constraints/ConstraintsOptionsExtensions.cs index 3c3642bfb0..3b834260c9 100644 --- a/Jint/Constraints/ConstraintsOptionsExtensions.cs +++ b/Jint/Constraints/ConstraintsOptionsExtensions.cs @@ -1,4 +1,4 @@ -using System.Threading; +using System.Threading; using Jint.Constraints; namespace Jint diff --git a/Jint/Constraints/MaxStatements.cs b/Jint/Constraints/MaxStatements.cs index d9e9a5f8b9..b14805bfa2 100644 --- a/Jint/Constraints/MaxStatements.cs +++ b/Jint/Constraints/MaxStatements.cs @@ -1,4 +1,4 @@ -using Jint.Runtime; +using Jint.Runtime; namespace Jint.Constraints { diff --git a/Jint/Constraints/MemoryLimit.cs b/Jint/Constraints/MemoryLimit.cs index 275249efd6..355d19c64b 100644 --- a/Jint/Constraints/MemoryLimit.cs +++ b/Jint/Constraints/MemoryLimit.cs @@ -1,10 +1,10 @@ -using Jint.Runtime; +using Jint.Runtime; namespace Jint.Constraints { internal sealed class MemoryLimit : IConstraint { - private static readonly Func GetAllocatedBytesForCurrentThread; + private static readonly Func? GetAllocatedBytesForCurrentThread; private readonly long _memoryLimit; private long _initialMemoryUsage; diff --git a/Jint/Constraints/TimeConstraint.cs b/Jint/Constraints/TimeConstraint.cs index 49b3dcdbd3..660dfde26b 100644 --- a/Jint/Constraints/TimeConstraint.cs +++ b/Jint/Constraints/TimeConstraint.cs @@ -1,4 +1,4 @@ -using Jint.Runtime; +using Jint.Runtime; namespace Jint.Constraints { diff --git a/Jint/Constraints/TimeConstraint2.cs b/Jint/Constraints/TimeConstraint2.cs index 08094deedb..399aba4413 100644 --- a/Jint/Constraints/TimeConstraint2.cs +++ b/Jint/Constraints/TimeConstraint2.cs @@ -1,4 +1,4 @@ -using Jint.Runtime; +using Jint.Runtime; using System.Threading; namespace Jint.Constraints @@ -6,7 +6,7 @@ namespace Jint.Constraints internal sealed class TimeConstraint2 : IConstraint { private readonly TimeSpan _timeout; - private CancellationTokenSource cts; + private CancellationTokenSource? _cts; public TimeConstraint2(TimeSpan timeout) { @@ -15,7 +15,7 @@ public TimeConstraint2(TimeSpan timeout) public void Check() { - if (cts.IsCancellationRequested) + if (_cts?.IsCancellationRequested == true) { ExceptionHelper.ThrowTimeoutException(); } @@ -23,12 +23,12 @@ public void Check() public void Reset() { - cts?.Dispose(); + _cts?.Dispose(); // This cancellation token source is very likely not disposed property, but it only allocates a timer, so not a big deal. // But using the cancellation token source is faster because we do not have to check the current time for each statement, // which means less system calls. - cts = new CancellationTokenSource(_timeout); + _cts = new CancellationTokenSource(_timeout); } } } diff --git a/Jint/DeclarationBindingType.cs b/Jint/DeclarationBindingType.cs index da03398af1..6f5a2fac41 100644 --- a/Jint/DeclarationBindingType.cs +++ b/Jint/DeclarationBindingType.cs @@ -1,4 +1,4 @@ -namespace Jint +namespace Jint { public enum DeclarationBindingType { diff --git a/Jint/Engine.Modules.cs b/Jint/Engine.Modules.cs index b59623a4ff..8dc1a2b8ba 100644 --- a/Jint/Engine.Modules.cs +++ b/Jint/Engine.Modules.cs @@ -1,6 +1,4 @@ -#nullable enable - -using Esprima; +using Esprima; using Jint.Native; using Jint.Native.Object; using Jint.Native.Promise; @@ -12,7 +10,7 @@ namespace Jint { public partial class Engine { - internal IModuleLoader ModuleLoader { get; set; } + internal IModuleLoader ModuleLoader { get; set; } = null!; private readonly Dictionary _modules = new(); private readonly Dictionary _builders = new(); @@ -140,7 +138,7 @@ private JsValue EvaluateModule(string specifier, ModuleRecord cyclicModule) { if (ownsContext) { - _activeEvaluationContext = null; + _activeEvaluationContext = null!; } } @@ -151,7 +149,7 @@ private JsValue EvaluateModule(string specifier, ModuleRecord cyclicModule) } else if (promise.State == PromiseState.Rejected) { - ExceptionHelper.ThrowJavaScriptException(this, promise.Value, new Completion(CompletionType.Throw, promise.Value, null, new Location(new Position(), new Position(), specifier))); + ExceptionHelper.ThrowJavaScriptException(this, promise.Value, new Completion(CompletionType.Throw, promise.Value!, null, new Location(new Position(), new Position(), specifier))); } else if (promise.State != PromiseState.Fulfilled) { diff --git a/Jint/Engine.cs b/Jint/Engine.cs index 2015b29904..39ac7a56dd 100644 --- a/Jint/Engine.cs +++ b/Jint/Engine.cs @@ -31,15 +31,15 @@ public sealed partial class Engine : IDisposable private readonly ExecutionContextStack _executionContexts; private JsValue _completionValue = JsValue.Undefined; - internal EvaluationContext _activeEvaluationContext; + internal EvaluationContext? _activeEvaluationContext; private readonly EventLoop _eventLoop = new(); // lazy properties - private DebugHandler _debugHandler; + private DebugHandler? _debugHandler; // cached access - internal readonly IObjectConverter[] _objectConverters; + internal readonly IObjectConverter[]? _objectConverters; private readonly IConstraint[] _constraints; internal readonly bool _isDebugMode; internal bool _isStrict; @@ -49,10 +49,10 @@ public sealed partial class Engine : IDisposable internal readonly JsValueArrayPool _jsValueArrayPool; internal readonly ExtensionMethodCache _extensionMethods; - public ITypeConverter ClrTypeConverter { get; internal set; } + public ITypeConverter ClrTypeConverter { get; internal set; } = null!; // cache of types used when resolving CLR type names - internal readonly Dictionary TypeCache = new(); + internal readonly Dictionary TypeCache = new(); // cache for already wrapped CLR objects to keep object identity internal readonly ConditionalWeakTable _objectWrapperCache = new(); @@ -60,20 +60,20 @@ public sealed partial class Engine : IDisposable internal readonly JintCallStack CallStack; // needed in initial engine setup, for example CLR function construction - internal Intrinsics _originalIntrinsics; - internal Host _host; + internal Intrinsics _originalIntrinsics = null!; + internal Host _host = null!; /// /// Constructs a new engine instance. /// - public Engine() : this((Action) null) + public Engine() : this((Action?) null) { } /// /// Constructs a new engine instance and allows customizing options. /// - public Engine(Action options) + public Engine(Action? options) : this((engine, opts) => options?.Invoke(opts)) { } @@ -133,7 +133,7 @@ internal ref readonly ExecutionContext ExecutionContext // temporary state for realm so that we can easily pass it to functions while still not // having a proper execution context established - internal Realm _realmInConstruction; + internal Realm? _realmInConstruction; public Realm Realm => _realmInConstruction ?? ExecutionContext.Realm; @@ -155,7 +155,7 @@ internal ExecutionContext EnterExecutionContext( EnvironmentRecord lexicalEnvironment, EnvironmentRecord variableEnvironment, Realm realm, - PrivateEnvironmentRecord privateEnvironment) + PrivateEnvironmentRecord? privateEnvironment) { var context = new ExecutionContext( null, @@ -293,7 +293,7 @@ private Engine ScriptEvaluation(ScriptRecord scriptRecord) Completion result; try { - result = list.Execute(_activeEvaluationContext); + result = list.Execute(_activeEvaluationContext!); } catch { @@ -374,7 +374,7 @@ internal void RunAvailableContinuations() } } - internal void RunBeforeExecuteStatementChecks(Statement statement) + internal void RunBeforeExecuteStatementChecks(Statement? statement) { // Avoid allocating the enumerator because we run this loop very often. foreach (var constraint in _constraints) @@ -449,7 +449,7 @@ internal JsValue GetValue(Reference reference, bool returnReferenceToPool) { // check if we are accessing a string, boxing operation can be costly to do index access // we have good chance to have fast path with integer or string indexer - ObjectInstance o = null; + ObjectInstance? o = null; if ((property._type & (InternalTypes.String | InternalTypes.Integer)) != 0 && baseValue is JsString s && TryHandleStringValue(property, s, ref o, out var jsValue)) @@ -473,7 +473,7 @@ internal JsValue GetValue(Reference reference, bool returnReferenceToPool) return desc.Value; } - var getter = desc.Get; + var getter = desc.Get!; if (getter.IsUndefined()) { return Undefined.Instance; @@ -500,7 +500,7 @@ internal JsValue GetValue(Reference reference, bool returnReferenceToPool) return bindingValue; } - private bool TryHandleStringValue(JsValue property, JsString s, ref ObjectInstance o, out JsValue jsValue) + private bool TryHandleStringValue(JsValue property, JsString s, ref ObjectInstance? o, out JsValue jsValue) { if (property == CommonProperties.Length) { @@ -587,7 +587,7 @@ public JsValue Invoke(string propertyName, params object[] arguments) /// The this value inside the function call. /// The arguments of the function call. /// The value returned by the function call. - public JsValue Invoke(string propertyName, object thisObj, object[] arguments) + public JsValue Invoke(string propertyName, object? thisObj, object[] arguments) { var value = GetValue(propertyName); @@ -612,7 +612,7 @@ public JsValue Invoke(JsValue value, params object[] arguments) /// The this value inside the function call. /// The arguments of the function call. /// The value returned by the function call. - public JsValue Invoke(JsValue value, object thisObj, object[] arguments) + public JsValue Invoke(JsValue value, object? thisObj, object[] arguments) { var callable = value as ICallable; if (callable is null) @@ -656,7 +656,7 @@ private T ExecuteWithConstraints(bool strict, Func callback) { if (ownsContext) { - _activeEvaluationContext = null; + _activeEvaluationContext = null!; } _isStrict = oldStrict; ResetConstraints(); @@ -685,7 +685,7 @@ internal JsValue Invoke(JsValue v, JsValue p, JsValue[] arguments) { if (ownsContext) { - _activeEvaluationContext = null; + _activeEvaluationContext = null!; } } } @@ -711,7 +711,7 @@ public JsValue GetValue(string propertyName) /// /// Gets the last evaluated . /// - internal Node GetLastSyntaxNode() + internal Node? GetLastSyntaxNode() { return _activeEvaluationContext?.LastSyntaxNode; } @@ -732,13 +732,13 @@ public JsValue GetValue(JsValue scope, JsValue property) /// /// https://tc39.es/ecma262/#sec-resolvebinding /// - internal Reference ResolveBinding(string name, EnvironmentRecord env = null) + internal Reference ResolveBinding(string name, EnvironmentRecord? env = null) { env ??= ExecutionContext.LexicalEnvironment; return GetIdentifierReference(env, name, StrictModeScope.IsStrictModeCode); } - private static Reference GetIdentifierReference(EnvironmentRecord env, string name, bool strict) + private static Reference GetIdentifierReference(EnvironmentRecord? env, string name, bool strict) { if (env is null) { @@ -757,11 +757,11 @@ private static Reference GetIdentifierReference(EnvironmentRecord env, string na /// /// https://tc39.es/ecma262/#sec-getnewtarget /// - internal JsValue GetNewTarget(EnvironmentRecord thisEnvironment = null) + internal JsValue GetNewTarget(EnvironmentRecord? thisEnvironment = null) { // we can take as argument if caller site has already determined the value, otherwise resolve thisEnvironment ??= ExecutionContext.GetThisEnvironment(); - return thisEnvironment.NewTarget; + return thisEnvironment.NewTarget ?? JsValue.Undefined; } /// @@ -796,7 +796,7 @@ private void GlobalDeclarationInstantiation( for (var i = functionDeclarations.Count - 1; i >= 0; i--) { var d = functionDeclarations[i]; - var fn = d.Id.Name; + var fn = d.Id!.Name!; if (!declaredFunctionNames.Contains(fn)) { var fnDefinable = env.CanDeclareGlobalFunction(fn); @@ -842,7 +842,7 @@ private void GlobalDeclarationInstantiation( } } - PrivateEnvironmentRecord privateEnv = null; + PrivateEnvironmentRecord? privateEnv = null; if (lexDeclarations != null) { for (var i = 0; i < lexDeclarations.Count; i++) @@ -874,7 +874,7 @@ private void GlobalDeclarationInstantiation( foreach (var f in functionToInitialize) { - var fn = f.Name; + var fn = f.Name!; if (env.HasLexicalDeclaration(fn)) { @@ -895,7 +895,7 @@ private void GlobalDeclarationInstantiation( /// /// https://tc39.es/ecma262/#sec-functiondeclarationinstantiation /// - internal ArgumentsInstance FunctionDeclarationInstantiation( + internal ArgumentsInstance? FunctionDeclarationInstantiation( FunctionInstance functionInstance, JsValue[] argumentsList) { @@ -915,7 +915,7 @@ internal ArgumentsInstance FunctionDeclarationInstantiation( var arguments = canInitializeParametersOnDeclaration ? argumentsList : null; env.InitializeParameters(parameterNames, hasDuplicates, arguments); - ArgumentsInstance ao = null; + ArgumentsInstance? ao = null; if (configuration.ArgumentsObjectNeeded) { if (strict || !simpleParameterList) @@ -942,7 +942,7 @@ internal ArgumentsInstance FunctionDeclarationInstantiation( if (!canInitializeParametersOnDeclaration) { // slower set - env.AddFunctionParameters(_activeEvaluationContext, func.Function, argumentsList); + env.AddFunctionParameters(_activeEvaluationContext!, func.Function, argumentsList); } // Let iteratorRecord be CreateListIteratorRecord(argumentsList). @@ -955,9 +955,10 @@ internal ArgumentsInstance FunctionDeclarationInstantiation( if (!hasParameterExpressions) { // NOTE: Only a single lexical environment is needed for the parameters and top-level vars. - for (var i = 0; i < configuration.VarsToInitialize.Count; i++) + var varsToInitialize = configuration.VarsToInitialize!; + for (var i = 0; i < varsToInitialize.Count; i++) { - var pair = configuration.VarsToInitialize[i]; + var pair = varsToInitialize[i]; env.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, JsValue.Undefined); } @@ -972,9 +973,10 @@ internal ArgumentsInstance FunctionDeclarationInstantiation( UpdateVariableEnvironment(varEnv); - for (var i = 0; i < configuration.VarsToInitialize.Count; i++) + var varsToInitialize = configuration.VarsToInitialize!; + for (var i = 0; i < varsToInitialize.Count; i++) { - var pair = configuration.VarsToInitialize[i]; + var pair = varsToInitialize[i]; var initialValue = pair.InitialValue ?? env.GetBindingValue(pair.Name, strict: false); varEnvRec.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, initialValue); } @@ -1024,7 +1026,7 @@ internal ArgumentsInstance FunctionDeclarationInstantiation( var realm = Realm; foreach (var f in configuration.FunctionsToInitialize) { - var fn = f.Name; + var fn = f.Name!; var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv, privateEnv); varEnv.SetMutableBinding(fn, fo, strict: false); } @@ -1055,7 +1057,7 @@ internal void EvalDeclarationInstantiation( Script script, EnvironmentRecord varEnv, EnvironmentRecord lexEnv, - PrivateEnvironmentRecord privateEnv, + PrivateEnvironmentRecord? privateEnv, bool strict) { var hoistingScope = HoistingScope.GetProgramLevelDeclarations(script); @@ -1074,7 +1076,7 @@ internal void EvalDeclarationInstantiation( { var variablesDeclaration = nodes[i]; var identifier = (Identifier) variablesDeclaration.Declarations[0].Id; - if (globalEnvironmentRecord.HasLexicalDeclaration(identifier.Name)) + if (globalEnvironmentRecord.HasLexicalDeclaration(identifier.Name!)) { ExceptionHelper.ThrowSyntaxError(realm, "Identifier '" + identifier.Name + "' has already been declared"); } @@ -1085,21 +1087,21 @@ internal void EvalDeclarationInstantiation( while (!ReferenceEquals(thisLex, varEnv)) { var thisEnvRec = thisLex; - if (!(thisEnvRec is ObjectEnvironmentRecord)) + if (thisEnvRec is not ObjectEnvironmentRecord) { ref readonly var nodes = ref hoistingScope._variablesDeclarations; for (var i = 0; i < nodes.Count; i++) { var variablesDeclaration = nodes[i]; var identifier = (Identifier) variablesDeclaration.Declarations[0].Id; - if (thisEnvRec.HasBinding(identifier.Name)) + if (thisEnvRec!.HasBinding(identifier.Name!)) { ExceptionHelper.ThrowSyntaxError(realm); } } } - thisLex = thisLex._outerEnv; + thisLex = thisLex!._outerEnv; } } @@ -1112,7 +1114,7 @@ internal void EvalDeclarationInstantiation( for (var i = functionDeclarations.Count - 1; i >= 0; i--) { var d = functionDeclarations[i]; - var fn = d.Id.Name; + var fn = d.Id!.Name!; if (!declaredFunctionNames.Contains(fn)) { if (varEnvRec is GlobalEnvironmentRecord ger) @@ -1136,7 +1138,7 @@ internal void EvalDeclarationInstantiation( var variableDeclarationsCount = variableDeclarations?.Count; for (var i = 0; i < variableDeclarationsCount; i++) { - var variableDeclaration = variableDeclarations[i]; + var variableDeclaration = variableDeclarations![i]; boundNames.Clear(); variableDeclaration.GetBoundNames(boundNames); for (var j = 0; j < boundNames.Count; j++) @@ -1163,7 +1165,7 @@ internal void EvalDeclarationInstantiation( for (var i = 0; i < lexicalDeclarationsCount; i++) { boundNames.Clear(); - var d = lexicalDeclarations[i]; + var d = lexicalDeclarations![i]; d.GetBoundNames(boundNames); for (var j = 0; j < boundNames.Count; j++) { @@ -1181,7 +1183,7 @@ internal void EvalDeclarationInstantiation( foreach (var f in functionsToInitialize) { - var fn = f.Name; + var fn = f.Name!; var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv, privateEnv); if (varEnvRec is GlobalEnvironmentRecord ger) { @@ -1233,7 +1235,7 @@ internal void UpdateVariableEnvironment(EnvironmentRecord newEnv) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void UpdatePrivateEnvironment(PrivateEnvironmentRecord newEnv) + internal void UpdatePrivateEnvironment(PrivateEnvironmentRecord? newEnv) { _executionContexts.ReplaceTopPrivateEnvironment(newEnv); } @@ -1281,7 +1283,7 @@ JsValue Callback() return ExecuteWithConstraints(Options.Strict, Callback); } - internal JsValue Call(ICallable callable, JsValue thisObject, JsValue[] arguments, JintExpression expression) + internal JsValue Call(ICallable callable, JsValue thisObject, JsValue[] arguments, JintExpression? expression) { if (callable is FunctionInstance functionInstance) { @@ -1328,7 +1330,7 @@ internal ObjectInstance Construct( JsValue constructor, JsValue[] arguments, JsValue newTarget, - JintExpression expression) + JintExpression? expression) { if (constructor is FunctionInstance functionInstance) { @@ -1342,7 +1344,7 @@ internal JsValue Call( FunctionInstance functionInstance, JsValue thisObject, JsValue[] arguments, - JintExpression expression) + JintExpression? expression) { var callStackElement = new CallStackElement(functionInstance, expression, ExecutionContext); var recursionDepth = CallStack.Push(callStackElement); @@ -1371,7 +1373,7 @@ private ObjectInstance Construct( FunctionInstance functionInstance, JsValue[] arguments, JsValue newTarget, - JintExpression expression) + JintExpression? expression) { var callStackElement = new CallStackElement(functionInstance, expression, ExecutionContext); var recursionDepth = CallStack.Push(callStackElement); diff --git a/Jint/EsprimaExtensions.cs b/Jint/EsprimaExtensions.cs index 6e0cc5455d..3bb5162c5a 100644 --- a/Jint/EsprimaExtensions.cs +++ b/Jint/EsprimaExtensions.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Runtime.CompilerServices; using Esprima; using Esprima.Ast; @@ -81,7 +79,7 @@ or Nodes.FunctionExpression or Nodes.YieldExpression) { var context = engine._activeEvaluationContext; - return JintExpression.Build(engine, expression).GetValue(context); + return JintExpression.Build(engine, expression).GetValue(context!); } return new Completion(CompletionType.Normal, JsValue.Undefined, expression.Location); @@ -265,7 +263,7 @@ internal static void BindingInitialization( if (expression is Identifier identifier) { var catchEnvRecord = (DeclarativeEnvironmentRecord) env; - catchEnvRecord.CreateMutableBindingAndInitialize(identifier.Name, canBeDeleted: false, value); + catchEnvRecord.CreateMutableBindingAndInitialize(identifier.Name!, canBeDeleted: false, value); } else if (expression is BindingPattern bindingPattern) { diff --git a/Jint/Extensions/JavascriptExtensions.cs b/Jint/Extensions/JavascriptExtensions.cs index d17ba632ea..b8a4e8d7a7 100644 --- a/Jint/Extensions/JavascriptExtensions.cs +++ b/Jint/Extensions/JavascriptExtensions.cs @@ -4,6 +4,11 @@ internal static class JavascriptExtensions { internal static string UpperToLowerCamelCase(this string str) { + if (char.IsLower(str[0])) + { + return str; + } + var arr = str.ToCharArray(); arr[0] = char.ToLowerInvariant(arr[0]); return new string(arr); diff --git a/Jint/Extensions/ReflectionExtensions.cs b/Jint/Extensions/ReflectionExtensions.cs index e1014644aa..1c2fcd9f60 100644 --- a/Jint/Extensions/ReflectionExtensions.cs +++ b/Jint/Extensions/ReflectionExtensions.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using Jint.Native; @@ -9,7 +10,7 @@ internal static class ReflectionExtensions { private static readonly Type nullableType = typeof(Nullable<>); - internal static void SetValue(this MemberInfo memberInfo, object forObject, object value) + internal static void SetValue(this MemberInfo memberInfo, object forObject, object? value) { if (memberInfo.MemberType == MemberTypes.Field) { @@ -35,7 +36,7 @@ internal static Type GetDefinedType(this MemberInfo memberInfo) { PropertyInfo propertyInfo => propertyInfo.PropertyType, FieldInfo fieldInfo => fieldInfo.FieldType, - _ => null + _ => null! }; } @@ -125,18 +126,18 @@ public static object AsNumberOfType(this double d, TypeCode type) } public static bool TryConvertViaTypeCoercion( - Type _memberType, + Type memberType, ValueCoercionType valueCoercionType, JsValue value, - out object converted) + [NotNullWhen(true)] out object? converted) { - if (_memberType == typeof(bool) && (valueCoercionType & ValueCoercionType.Boolean) != 0) + if (memberType == typeof(bool) && (valueCoercionType & ValueCoercionType.Boolean) != 0) { converted = TypeConverter.ToBoolean(value); return true; } - if (_memberType == typeof(string) + if (memberType == typeof(string) && !value.IsNullOrUndefined() && (valueCoercionType & ValueCoercionType.String) != 0) { @@ -146,12 +147,12 @@ public static bool TryConvertViaTypeCoercion( return true; } - if (_memberType.IsClrNumericCoercible() && (valueCoercionType & ValueCoercionType.Number) != 0) + if (memberType.IsClrNumericCoercible() && (valueCoercionType & ValueCoercionType.Number) != 0) { // we know how to print out correct string presentation for primitives // that are non-null and non-undefined var number = TypeConverter.ToNumber(value); - converted = number.AsNumberOfType(Type.GetTypeCode(_memberType)); + converted = number.AsNumberOfType(Type.GetTypeCode(memberType)); return true; } diff --git a/Jint/HoistingScope.cs b/Jint/HoistingScope.cs index f3264e6af9..84f4f0e5f1 100644 --- a/Jint/HoistingScope.cs +++ b/Jint/HoistingScope.cs @@ -5,20 +5,20 @@ namespace Jint { internal readonly struct HoistingScope { - internal readonly List _functionDeclarations; + internal readonly List? _functionDeclarations; - internal readonly List _variablesDeclarations; - internal readonly List _varNames; + internal readonly List? _variablesDeclarations; + internal readonly List? _varNames; - internal readonly List _lexicalDeclarations; - internal readonly List _lexicalNames; + internal readonly List? _lexicalDeclarations; + internal readonly List? _lexicalNames; private HoistingScope( - List functionDeclarations, - List varNames, - List variableDeclarations, - List lexicalDeclarations, - List lexicalNames) + List? functionDeclarations, + List? varNames, + List? variableDeclarations, + List? lexicalDeclarations, + List? lexicalNames) { _functionDeclarations = functionDeclarations; _varNames = varNames; @@ -74,9 +74,9 @@ public static HoistingScope GetModuleLevelDeclarations( treeWalker._lexicalNames); } - public static List GetLexicalDeclarations(BlockStatement statement) + public static List? GetLexicalDeclarations(BlockStatement statement) { - List lexicalDeclarations = null; + List? lexicalDeclarations = null; ref readonly var statementListItems = ref statement.Body; for (var i = 0; i < statementListItems.Count; i++) { @@ -98,9 +98,9 @@ public static List GetLexicalDeclarations(BlockStatement statement) return lexicalDeclarations; } - public static List GetLexicalDeclarations(SwitchCase statement) + public static List? GetLexicalDeclarations(SwitchCase statement) { - List lexicalDeclarations = null; + List? lexicalDeclarations = null; ref readonly var statementListItems = ref statement.Consequent; for (var i = 0; i < statementListItems.Count; i++) { @@ -126,7 +126,7 @@ public static List GetLexicalDeclarations(SwitchCase statement) public static void GetImportsAndExports( Module module, out HashSet requestedModules, - out List importEntries, + out List? importEntries, out List localExportEntries, out List indirectExportEntries, out List starExportEntries) @@ -203,16 +203,16 @@ public static void GetImportsAndExports( private sealed class ScriptWalker { - internal List _functions; + internal List? _functions; private readonly bool _strict; private readonly bool _collectVarNames; - internal List _variableDeclarations; - internal List _varNames; + internal List? _variableDeclarations; + internal List? _varNames; private readonly bool _collectLexicalNames; - internal List _lexicalDeclarations; - internal List _lexicalNames; + internal List? _lexicalDeclarations; + internal List? _lexicalNames; public ScriptWalker(bool strict, bool collectVarNames, bool collectLexicalNames) { @@ -221,7 +221,7 @@ public ScriptWalker(bool strict, bool collectVarNames, bool collectLexicalNames) _collectLexicalNames = collectLexicalNames; } - public void Visit(Node node, Node parent) + public void Visit(Node node, Node? parent) { foreach (var childNode in node.ChildNodes) { @@ -246,7 +246,7 @@ public void Visit(Node node, Node parent) { if (declaration.Id is Identifier identifier) { - _varNames.Add(identifier.Name); + _varNames.Add(identifier.Name!); } } } @@ -264,7 +264,7 @@ public void Visit(Node node, Node parent) { if (declaration.Id is Identifier identifier) { - _lexicalNames.Add(identifier.Name); + _lexicalNames.Add(identifier.Name!); } } } @@ -297,9 +297,9 @@ public void Visit(Node node, Node parent) private sealed class ModuleWalker { - internal List _importEntries; - internal List _exportEntries; - internal HashSet _requestedModules; + internal List? _importEntries; + internal List? _exportEntries; + internal HashSet? _requestedModules; internal void Visit(Node node) { @@ -314,7 +314,7 @@ internal void Visit(Node node) { _importEntries ??= new(); _requestedModules ??= new(); - var import = childNode as ImportDeclaration; + var import = (ImportDeclaration) childNode; import.GetImportEntries(_importEntries, _requestedModules); } else if (childNode.Type == Nodes.ExportAllDeclaration || diff --git a/Jint/IConstraint.cs b/Jint/IConstraint.cs index ab4c1a27dd..5c491ffce2 100644 --- a/Jint/IConstraint.cs +++ b/Jint/IConstraint.cs @@ -1,4 +1,4 @@ -namespace Jint +namespace Jint { public interface IConstraint { diff --git a/Jint/Jint.csproj b/Jint/Jint.csproj index 768adca7ee..443234c8eb 100644 --- a/Jint/Jint.csproj +++ b/Jint/Jint.csproj @@ -7,6 +7,7 @@ latest true enable + enable diff --git a/Jint/JsValueExtensions.cs b/Jint/JsValueExtensions.cs index 9d0299c1d7..d057b74a4f 100644 --- a/Jint/JsValueExtensions.cs +++ b/Jint/JsValueExtensions.cs @@ -1,4 +1,4 @@ -using System.Diagnostics.Contracts; +using System.Diagnostics.Contracts; using System.Numerics; using System.Runtime.CompilerServices; using Esprima; @@ -135,7 +135,7 @@ public static DateInstance AsDate(this JsValue value) ExceptionHelper.ThrowArgumentException("The value is not a date"); } - return value as DateInstance; + return (DateInstance) value; } [Pure] @@ -146,7 +146,7 @@ public static RegExpInstance AsRegExp(this JsValue value) ExceptionHelper.ThrowArgumentException("The value is not a regex"); } - return value as RegExpInstance; + return (RegExpInstance) value; } [Pure] @@ -158,7 +158,7 @@ public static ObjectInstance AsObject(this JsValue value) ExceptionHelper.ThrowArgumentException("The value is not an object"); } - return value as ObjectInstance; + return (ObjectInstance) value; } [Pure] @@ -170,7 +170,7 @@ public static TInstance AsInstance(this JsValue value) where TInstanc ExceptionHelper.ThrowArgumentException("The value is not an object"); } - return value as TInstance; + return (value as TInstance)!; } [Pure] @@ -182,7 +182,7 @@ public static ArrayInstance AsArray(this JsValue value) ExceptionHelper.ThrowArgumentException("The value is not an array"); } - return value as ArrayInstance; + return (ArrayInstance) value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -385,14 +385,14 @@ public static ulong[] AsBigUint64Array(this JsValue value) [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static T TryCast(this JsValue value) where T : class + public static T? TryCast(this JsValue value) where T : class { return value as T; } [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static T TryCast(this JsValue value, Action fail) where T : class + public static T? TryCast(this JsValue value, Action fail) where T : class { if (value is T o) { @@ -406,7 +406,7 @@ public static T TryCast(this JsValue value, Action fail) where T : c [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static T As(this JsValue value) where T : ObjectInstance + public static T? As(this JsValue value) where T : ObjectInstance { if (value.IsObject()) { @@ -423,7 +423,7 @@ public static FunctionInstance AsFunctionInstance(this JsValue value) if (value is not FunctionInstance instance) { ThrowWrongTypeException(value, "FunctionInstance"); - return null; + return null!; } return instance; diff --git a/Jint/ModuleBuilder.cs b/Jint/ModuleBuilder.cs index b8a33f1c97..ccd6725ea8 100644 --- a/Jint/ModuleBuilder.cs +++ b/Jint/ModuleBuilder.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima; using Esprima.Ast; using Jint.Native; diff --git a/Jint/Native/AggregateError/AggregateErrorConstructor.cs b/Jint/Native/AggregateError/AggregateErrorConstructor.cs index 7c31e8e88c..0e8c75bcf3 100644 --- a/Jint/Native/AggregateError/AggregateErrorConstructor.cs +++ b/Jint/Native/AggregateError/AggregateErrorConstructor.cs @@ -1,5 +1,3 @@ -#nullable enable - using Jint.Native.Error; using Jint.Native.Function; using Jint.Native.Object; diff --git a/Jint/Native/AggregateError/AggregateErrorPrototype.cs b/Jint/Native/AggregateError/AggregateErrorPrototype.cs index 60df3e3261..6e6728dfd2 100644 --- a/Jint/Native/AggregateError/AggregateErrorPrototype.cs +++ b/Jint/Native/AggregateError/AggregateErrorPrototype.cs @@ -1,5 +1,3 @@ -#nullable enable - using Jint.Collections; using Jint.Native.Object; using Jint.Runtime; diff --git a/Jint/Native/Argument/ArgumentsInstance.cs b/Jint/Native/Argument/ArgumentsInstance.cs index bb496b5b0e..2c932a5a70 100644 --- a/Jint/Native/Argument/ArgumentsInstance.cs +++ b/Jint/Native/Argument/ArgumentsInstance.cs @@ -1,4 +1,4 @@ -using System.Threading; +using System.Threading; using Jint.Native.Function; using Jint.Native.Object; using Jint.Native.Symbol; @@ -16,12 +16,12 @@ namespace Jint.Native.Argument public sealed class ArgumentsInstance : ObjectInstance { // cache property container for array iteration for less allocations - private static readonly ThreadLocal> _mappedNamed = new ThreadLocal>(() => new HashSet()); + private static readonly ThreadLocal> _mappedNamed = new(() => new HashSet()); - private FunctionInstance _func; - private Key[] _names; - private JsValue[] _args; - private DeclarativeEnvironmentRecord _env; + private FunctionInstance _func = null!; + private Key[] _names = null!; + private JsValue[] _args = null!; + private DeclarativeEnvironmentRecord _env = null!; private bool _canReturnToPool; private bool _hasRestParameter; private bool _materialized; @@ -70,7 +70,7 @@ protected override void Initialize() } else { - ObjectInstance map = null; + ObjectInstance? map = null; if (args.Length > 0) { var mappedNamed = _mappedNamed.Value; @@ -102,7 +102,7 @@ protected override void Initialize() DefinePropertyOrThrow(GlobalSymbolRegistry.Iterator, new PropertyDescriptor(iteratorFunction, PropertyFlag.Writable | PropertyFlag.Configurable)); } - public ObjectInstance ParameterMap { get; set; } + public ObjectInstance? ParameterMap { get; set; } internal override bool IsIntegerIndexedArray => true; diff --git a/Jint/Native/Array/ArrayConstructor.cs b/Jint/Native/Array/ArrayConstructor.cs index 5e4aa9cb36..e4e79cb71a 100644 --- a/Jint/Native/Array/ArrayConstructor.cs +++ b/Jint/Native/Array/ArrayConstructor.cs @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; using Jint.Collections; using Jint.Native.Function; using Jint.Native.Iterator; @@ -105,7 +105,7 @@ private JsValue From(JsValue thisObj, JsValue[] arguments) private ObjectInstance ConstructArrayFromArrayLike( JsValue thisObj, ObjectInstance objectInstance, - ICallable callable, + ICallable? callable, JsValue thisArg) { var source = ArrayOperations.For(objectInstance); @@ -137,7 +137,7 @@ private ObjectInstance ConstructArrayFromArrayLike( source.TryGetValue(i, out var value); if (!ReferenceEquals(callable, null)) { - args[0] = value; + args![0] = value; args[1] = i; jsValue = callable.Call(thisArg, args); @@ -155,7 +155,7 @@ private ObjectInstance ConstructArrayFromArrayLike( if (!ReferenceEquals(callable, null)) { - _engine._jsValueArrayPool.ReturnArray(args); + _engine._jsValueArrayPool.ReturnArray(args!); } target.SetLength(length); @@ -166,7 +166,7 @@ private sealed class ArrayProtocol : IteratorProtocol { private readonly JsValue _thisArg; private readonly ArrayOperations _instance; - private readonly ICallable _callable; + private readonly ICallable? _callable; private long _index = -1; public ArrayProtocol( @@ -174,7 +174,7 @@ public ArrayProtocol( JsValue thisArg, ObjectInstance instance, IteratorInstance iterator, - ICallable callable) : base(engine, iterator, 2) + ICallable? callable) : base(engine, iterator, 2) { _thisArg = thisArg; _instance = ArrayOperations.For(instance); @@ -351,7 +351,7 @@ private ArrayInstance Construct(JsValue[] arguments, ulong capacity, ObjectInsta /// /// https://tc39.es/ecma262/#sec-arraycreate /// - internal ArrayInstance ArrayCreate(ulong length, ObjectInstance proto = null) + internal ArrayInstance ArrayCreate(ulong length, ObjectInstance? proto = null) { if (length > ArrayOperations.MaxArrayLength) { diff --git a/Jint/Native/Array/ArrayInstance.cs b/Jint/Native/Array/ArrayInstance.cs index 71e114da30..395170832e 100644 --- a/Jint/Native/Array/ArrayInstance.cs +++ b/Jint/Native/Array/ArrayInstance.cs @@ -1,4 +1,5 @@ -using System.Collections; +using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Jint.Native.Object; using Jint.Native.Symbol; @@ -9,13 +10,13 @@ namespace Jint.Native.Array { public class ArrayInstance : ObjectInstance, IEnumerable { - internal PropertyDescriptor _length; + internal PropertyDescriptor? _length; private const int MaxDenseArrayLength = 10_000_000; // we have dense and sparse, we usually can start with dense and fall back to sparse when necessary - internal PropertyDescriptor[] _dense; - private Dictionary _sparse; + internal PropertyDescriptor?[]? _dense; + private Dictionary? _sparse; private ObjectChangeFlags _objectChangeFlags; @@ -28,11 +29,11 @@ public ArrayInstance(Engine engine, uint capacity = 0) : base(engine) if (capacity < MaxDenseArrayLength) { - _dense = capacity > 0 ? new PropertyDescriptor[capacity] : System.Array.Empty(); + _dense = capacity > 0 ? new PropertyDescriptor?[capacity] : System.Array.Empty(); } else { - _sparse = new Dictionary((int) (capacity <= 1024 ? capacity : 1024)); + _sparse = new Dictionary((int) (capacity <= 1024 ? capacity : 1024)); } } @@ -56,7 +57,7 @@ public ArrayInstance(Engine engine, PropertyDescriptor[] items) : base(engine) _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable); } - public ArrayInstance(Engine engine, Dictionary items) : base(engine) + public ArrayInstance(Engine engine, Dictionary items) : base(engine) { _sparse = items; var length = items?.Count ?? 0; @@ -132,7 +133,7 @@ public sealed override bool DefineOwnProperty(JsValue property, PropertyDescript } var oldLenDesc = _length; - var oldLen = (uint) TypeConverter.ToNumber(oldLenDesc.Value); + var oldLen = (uint) TypeConverter.ToNumber(oldLenDesc!.Value); newLenDesc.Value = newLen; if (newLen >= oldLen) @@ -162,7 +163,7 @@ public sealed override bool DefineOwnProperty(JsValue property, PropertyDescript return false; } - var count = _dense?.Length ?? _sparse.Count; + var count = _dense?.Length ?? _sparse!.Count; if (count < oldLen - newLen) { if (_dense != null) @@ -196,7 +197,7 @@ public sealed override bool DefineOwnProperty(JsValue property, PropertyDescript { // in the case of sparse arrays, treat each concrete element instead of // iterating over all indexes - var keys = new List(_sparse.Keys); + var keys = new List(_sparse!.Keys); var keysCount = keys.Count; for (var i = 0; i < keysCount; i++) { @@ -256,7 +257,7 @@ public sealed override bool DefineOwnProperty(JsValue property, PropertyDescript private bool DefineOwnProperty(uint index, PropertyDescriptor desc) { var oldLenDesc = _length; - var oldLen = (uint) TypeConverter.ToNumber(oldLenDesc.Value); + var oldLen = (uint) TypeConverter.ToNumber(oldLenDesc!.Value); if (index >= oldLen && !oldLenDesc.Writable) { @@ -286,7 +287,7 @@ internal uint GetLength() return 0; } - return (uint) ((JsNumber) _length._value)._value; + return (uint) ((JsNumber) _length._value!)._value; } protected sealed override void AddProperty(JsValue property, PropertyDescriptor descriptor) @@ -300,7 +301,7 @@ protected sealed override void AddProperty(JsValue property, PropertyDescriptor base.AddProperty(property, descriptor); } - protected sealed override bool TryGetProperty(JsValue property, out PropertyDescriptor descriptor) + protected sealed override bool TryGetProperty(JsValue property, [NotNullWhen(true)] out PropertyDescriptor? descriptor) { if (property == CommonProperties.Length) { @@ -318,13 +319,14 @@ public sealed override List GetOwnPropertyKeys(Types types = Types.None return base.GetOwnPropertyKeys(types); } - var properties = new List(_dense?.Length ?? 0 + 1); - if (_dense != null) + var temp = _dense; + var properties = new List(temp?.Length ?? 0 + 1); + if (temp != null) { - var length = System.Math.Min(_dense.Length, GetLength()); + var length = System.Math.Min(temp.Length, GetLength()); for (var i = 0; i < length; i++) { - if (_dense[i] != null) + if (temp[i] != null) { properties.Add(JsString.Create(i)); } @@ -332,7 +334,7 @@ public sealed override List GetOwnPropertyKeys(Types types = Types.None } else { - foreach (var entry in _sparse) + foreach (var entry in _sparse!) { properties.Add(JsString.Create(entry.Key)); } @@ -350,22 +352,28 @@ public sealed override List GetOwnPropertyKeys(Types types = Types.None public sealed override IEnumerable> GetOwnProperties() { - if (_dense != null) + var temp = _dense; + if (temp != null) { - var length = System.Math.Min(_dense.Length, GetLength()); + var length = System.Math.Min(temp.Length, GetLength()); for (var i = 0; i < length; i++) { - if (_dense[i] != null) + var descriptor = temp[i]; + if (descriptor != null) { - yield return new KeyValuePair(TypeConverter.ToString(i), _dense[i]); + yield return new KeyValuePair(TypeConverter.ToString(i), descriptor); } } } else { - foreach (var entry in _sparse) + foreach (var entry in _sparse!) { - yield return new KeyValuePair(TypeConverter.ToString(entry.Key), entry.Value); + var descriptor = entry.Value; + if (descriptor is not null) + { + yield return new KeyValuePair(TypeConverter.ToString(entry.Key), descriptor); + } } } @@ -581,7 +589,7 @@ private static uint StringAsIndex(int d, string p) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void SetIndexValue(uint index, JsValue value, bool updateLength) + internal void SetIndexValue(uint index, JsValue? value, bool updateLength) { if (updateLength) { @@ -603,7 +611,7 @@ private void EnsureCorrectLength(uint index) [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void SetLength(uint length) { - _length.Value = length; + _length!.Value = length; } internal uint GetSmallestIndex() @@ -615,7 +623,7 @@ internal uint GetSmallestIndex() uint smallest = 0; // only try to help if collection reasonable small - if (_sparse.Count > 0 && _sparse.Count < 100 && !_sparse.ContainsKey(0)) + if (_sparse!.Count > 0 && _sparse.Count < 100 && !_sparse.ContainsKey(0)) { smallest = uint.MaxValue; foreach (var key in _sparse.Keys) @@ -679,7 +687,7 @@ internal bool DeleteAt(uint index) } else { - return _sparse.Remove(index); + return _sparse!.Remove(index); } return false; @@ -687,7 +695,7 @@ internal bool DeleteAt(uint index) [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool TryGetDescriptor(uint index, out PropertyDescriptor descriptor) + private bool TryGetDescriptor(uint index, [NotNullWhen(true)] out PropertyDescriptor? descriptor) { var temp = _dense; if (temp != null) @@ -700,7 +708,7 @@ private bool TryGetDescriptor(uint index, out PropertyDescriptor descriptor) return descriptor != null; } - return _sparse.TryGetValue(index, out descriptor); + return _sparse!.TryGetValue(index, out descriptor); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -718,7 +726,7 @@ internal void WriteArrayValue(uint index, PropertyDescriptor desc) if (canUseDense) { - if (index >= (uint) _dense.Length) + if (index >= (uint) _dense!.Length) { EnsureCapacity((uint) newSize); } @@ -731,13 +739,13 @@ internal void WriteArrayValue(uint index, PropertyDescriptor desc) { ConvertToSparse(); } - _sparse[index] = desc; + _sparse![index] = desc; } } private void ConvertToSparse() { - _sparse = new Dictionary(_dense.Length <= 1024 ? _dense.Length : 0); + _sparse = new Dictionary(_dense!.Length <= 1024 ? _dense.Length : 0); // need to move data for (uint i = 0; i < (uint) _dense.Length; ++i) { @@ -797,7 +805,8 @@ internal uint Push(JsValue[] arguments) EnsureCapacity((uint) newLength); } - var canUseDirectIndexSet = _dense != null && newLength <= _dense.Length; + var temp = _dense; + var canUseDirectIndexSet = temp != null && newLength <= temp.Length; double n = initialLength; foreach (var argument in arguments) @@ -805,7 +814,7 @@ internal uint Push(JsValue[] arguments) var desc = new PropertyDescriptor(argument, PropertyFlag.ConfigurableEnumerableWritable); if (canUseDirectIndexSet) { - _dense[(uint) n] = desc; + temp![(uint) n] = desc; } else { @@ -818,7 +827,7 @@ internal uint Push(JsValue[] arguments) // check if we can set length fast without breaking ECMA specification if (n < uint.MaxValue && CanSetLength()) { - _length.Value = (uint) n; + _length!.Value = (uint) n; } else { @@ -833,7 +842,7 @@ internal uint Push(JsValue[] arguments) private bool CanSetLength() { - if (!_length.IsAccessorDescriptor()) + if (!_length!.IsAccessorDescriptor()) { return _length.Writable; } @@ -1021,7 +1030,7 @@ internal void CopyValues(ArrayInstance source, uint sourceStartIndex, uint targe public sealed override string ToString() { // debugger can make things hard when evaluates computed values - return "(" + (_length?._value.AsNumber() ?? 0) + ")[]"; + return "(" + (_length?._value!.AsNumber() ?? 0) + ")[]"; } private static void ThrowMaximumArraySizeReachedException(Engine engine, uint capacity) diff --git a/Jint/Native/Array/ArrayIteratorPrototype.cs b/Jint/Native/Array/ArrayIteratorPrototype.cs index 89a90da382..8cd3d9935f 100644 --- a/Jint/Native/Array/ArrayIteratorPrototype.cs +++ b/Jint/Native/Array/ArrayIteratorPrototype.cs @@ -30,8 +30,8 @@ internal IteratorInstance Construct(ObjectInstance array, ArrayIteratorType kind private sealed class ArrayLikeIterator : IteratorInstance { private readonly ArrayIteratorType _kind; - private readonly TypedArrayInstance _typedArray; - private readonly ArrayOperations _operations; + private readonly TypedArrayInstance? _typedArray; + private readonly ArrayOperations? _operations; private uint _position; private bool _closed; @@ -57,12 +57,11 @@ public override bool TryIteratorStep(out ObjectInstance nextItem) } else { - len = _operations.GetLength(); + len = _operations!.GetLength(); } if (!_closed && _position < len) { - JsValue value; if (_typedArray is not null) { nextItem = _kind switch @@ -74,7 +73,7 @@ public override bool TryIteratorStep(out ObjectInstance nextItem) } else { - _operations.TryGetValue(_position, out value); + _operations!.TryGetValue(_position, out var value); if (_kind == ArrayIteratorType.Key) { nextItem = new ValueIteratorPosition(_engine, _position); @@ -99,4 +98,4 @@ public override bool TryIteratorStep(out ObjectInstance nextItem) } } } -} \ No newline at end of file +} diff --git a/Jint/Native/Array/ArrayOperations.cs b/Jint/Native/Array/ArrayOperations.cs index 28e1f11cb9..1610afe194 100644 --- a/Jint/Native/Array/ArrayOperations.cs +++ b/Jint/Native/Array/ArrayOperations.cs @@ -102,16 +102,16 @@ public JsValue Current { if (!_initialized) { - return null; + return JsValue.Undefined; } else { - return _obj.TryGetValue(_current, out var temp) ? temp : null; + return _obj.TryGetValue(_current, out var temp) ? temp : JsValue.Undefined; } } } - object IEnumerator.Current => Current; + object? IEnumerator.Current => Current; public void Dispose() { @@ -216,10 +216,10 @@ public override ulong GetSmallestIndex(ulong length) => _target.GetSmallestIndex(); public override uint GetLength() - => (uint) ((JsNumber) _target._length._value)._value; + => (uint) ((JsNumber) _target._length!._value!)._value; public override ulong GetLongLength() - => (ulong) ((JsNumber) _target._length._value)._value; + => (ulong) ((JsNumber) _target._length!._value!)._value; public override void SetLength(ulong length) => _target.Set(CommonProperties.Length, length, true); diff --git a/Jint/Native/Array/ArrayPrototype.cs b/Jint/Native/Array/ArrayPrototype.cs index c3d9f90ec9..12ed987fa3 100644 --- a/Jint/Native/Array/ArrayPrototype.cs +++ b/Jint/Native/Array/ArrayPrototype.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Iterator; using Jint.Native.Number; using Jint.Native.Object; @@ -18,7 +18,7 @@ public sealed class ArrayPrototype : ArrayInstance { private readonly Realm _realm; private readonly ArrayConstructor _constructor; - internal ClrFunctionInstance _originalIteratorFunction; + internal ClrFunctionInstance? _originalIteratorFunction; internal ArrayPrototype( Engine engine, @@ -81,7 +81,7 @@ protected override void Initialize() [GlobalSymbolRegistry.Iterator] = new PropertyDescriptor(_originalIteratorFunction, propertyFlags), [GlobalSymbolRegistry.Unscopables] = new LazyPropertyDescriptor(_engine, static state => { - var unscopables = new ObjectInstance((Engine) state) + var unscopables = new ObjectInstance((Engine) state!) { _prototype = null }; @@ -526,8 +526,8 @@ private long FlattenIntoArray( uint sourceLen, long start, double depth, - ICallable mapperFunction = null, - JsValue thisArg = null) + ICallable? mapperFunction = null, + JsValue? thisArg = null) { var targetIndex = start; var sourceIndex = 0; @@ -550,7 +550,7 @@ private long FlattenIntoArray( { callArguments[0] = element; callArguments[1] = JsNumber.Create(sourceIndex); - element = mapperFunction.Call(thisArg, callArguments); + element = mapperFunction.Call(thisArg ?? Undefined, callArguments); } var shouldFlatten = false; @@ -1004,7 +1004,7 @@ private JsValue Sort(JsValue thisObj, JsValue[] arguments) var obj = ArrayOperations.For(objectInstance); var compareArg = arguments.At(0); - ICallable compareFn = null; + ICallable? compareFn = null; if (!compareArg.IsUndefined()) { if (compareArg is not ICallable callable) @@ -1036,7 +1036,7 @@ private JsValue Sort(JsValue thisObj, JsValue[] arguments) // don't eat inner exceptions try { - var array = items.OrderBy(x => x, ArrayComparer.WithFunction(_engine, compareFn)).ToArray(); + var array = items.OrderBy(x => x, ArrayComparer.WithFunction(_engine, compareFn!)).ToArray(); uint j; for (j = 0; j < itemCount; ++j) @@ -1176,20 +1176,20 @@ private JsValue Reverse(JsValue thisObj, JsValue[] arguments) if (lowerExists && upperExists) { - o.Set(lower, upperValue, throwOnError: true); - o.Set(upper, lowerValue, throwOnError: true); + o.Set(lower, upperValue!, throwOnError: true); + o.Set(upper, lowerValue!, throwOnError: true); } if (!lowerExists && upperExists) { - o.Set(lower, upperValue, throwOnError: true); + o.Set(lower, upperValue!, throwOnError: true); o.DeletePropertyOrThrow(upper); } if (lowerExists && !upperExists) { o.DeletePropertyOrThrow(lower); - o.Set(upper, lowerValue, throwOnError: true); + o.Set(upper, lowerValue!, throwOnError: true); } lower++; @@ -1479,11 +1479,11 @@ public static ArrayComparer WithFunction(Engine engine, ICallable compare) return new ArrayComparer(engine, compare); } - private readonly Engine _engine; - private readonly ICallable _compare; + private readonly Engine? _engine; + private readonly ICallable? _compare; private readonly JsValue[] _comparableArray = new JsValue[2]; - private ArrayComparer(Engine engine, ICallable compare) + private ArrayComparer(Engine? engine, ICallable? compare) { _engine = engine; _compare = compare; @@ -1511,8 +1511,8 @@ public int Compare(JsValue x, JsValue y) } } - var xUndefined = x.IsUndefined(); - var yUndefined = y.IsUndefined(); + var xUndefined = x!.IsUndefined(); + var yUndefined = y!.IsUndefined(); if (xUndefined && yUndefined) { return 0; @@ -1530,10 +1530,10 @@ public int Compare(JsValue x, JsValue y) if (_compare != null) { - _engine.RunBeforeExecuteStatementChecks(null); + _engine!.RunBeforeExecuteStatementChecks(null); - _comparableArray[0] = x; - _comparableArray[1] = y; + _comparableArray[0] = x!; + _comparableArray[1] = y!; var s = TypeConverter.ToNumber(_compare.Call(Undefined, _comparableArray)); if (s < 0) @@ -1549,8 +1549,8 @@ public int Compare(JsValue x, JsValue y) return 0; } - var xString = TypeConverter.ToString(x); - var yString = TypeConverter.ToString(y); + var xString = TypeConverter.ToString(x!); + var yString = TypeConverter.ToString(y!); return string.CompareOrdinal(xString, yString); } diff --git a/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs b/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs index b60c41f1cc..4c838e13ab 100644 --- a/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs +++ b/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs @@ -87,7 +87,7 @@ internal ArrayBufferInstance AllocateArrayBuffer(JsValue constructor, ulong byte var obj = OrdinaryCreateFromConstructor( constructor, static intrinsics => intrinsics.ArrayBuffer.PrototypeObject, - static (engine, realm, state) => new ArrayBufferInstance(engine, (ulong) ((JsNumber) state)._value), + static (engine, realm, state) => new ArrayBufferInstance(engine, (ulong) ((JsNumber) state!)._value), JsNumber.Create(byteLength)); return obj; diff --git a/Jint/Native/ArrayBuffer/ArrayBufferInstance.cs b/Jint/Native/ArrayBuffer/ArrayBufferInstance.cs index b93199d676..20f841c32f 100644 --- a/Jint/Native/ArrayBuffer/ArrayBufferInstance.cs +++ b/Jint/Native/ArrayBuffer/ArrayBufferInstance.cs @@ -12,7 +12,7 @@ public sealed class ArrayBufferInstance : ObjectInstance // so that we don't need to allocate while or reading setting values private readonly byte[] _workBuffer = new byte[8]; - private byte[] _arrayBufferData; + private byte[]? _arrayBufferData; private readonly JsValue _arrayBufferDetachKey = Undefined; internal ArrayBufferInstance( @@ -33,8 +33,8 @@ private byte[] CreateByteDataBlock(ulong byteLength) return new byte[byteLength]; } - internal int ArrayBufferByteLength => _arrayBufferData.Length; - internal byte[] ArrayBufferData => _arrayBufferData; + internal int ArrayBufferByteLength => _arrayBufferData?.Length ?? 0; + internal byte[]? ArrayBufferData => _arrayBufferData; internal bool IsDetachedBuffer => _arrayBufferData is null; internal bool IsSharedArrayBuffer => false; // TODO SharedArrayBuffer @@ -42,7 +42,7 @@ private byte[] CreateByteDataBlock(ulong byteLength) /// /// https://tc39.es/ecma262/#sec-detacharraybuffer /// - internal void DetachArrayBuffer(JsValue key = null) + internal void DetachArrayBuffer(JsValue? key = null) { key ??= Undefined; @@ -111,7 +111,7 @@ g. Append readEvent to eventList. internal TypedArrayValue RawBytesToNumeric(TypedArrayElementType type, int byteIndex, bool isLittleEndian) { var elementSize = type.GetElementSize(); - var rawBytes = _arrayBufferData; + var rawBytes = _arrayBufferData!; // 8 byte values require a little more at the moment var needsReverse = !isLittleEndian diff --git a/Jint/Native/ArrayBuffer/ArrayBufferOrder.cs b/Jint/Native/ArrayBuffer/ArrayBufferOrder.cs index 06be14496c..74bb48a71f 100644 --- a/Jint/Native/ArrayBuffer/ArrayBufferOrder.cs +++ b/Jint/Native/ArrayBuffer/ArrayBufferOrder.cs @@ -6,4 +6,4 @@ internal enum ArrayBufferOrder SecCst, Unordered } -} \ No newline at end of file +} diff --git a/Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs b/Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs index 30fda25716..0c42afcefa 100644 --- a/Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs +++ b/Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs @@ -155,4 +155,4 @@ private JsValue Slice(JsValue thisObj, JsValue[] arguments) return bufferInstance; } } -} \ No newline at end of file +} diff --git a/Jint/Native/BigInt/BigIntConstructor.cs b/Jint/Native/BigInt/BigIntConstructor.cs index d0133f1c05..1e440c5874 100644 --- a/Jint/Native/BigInt/BigIntConstructor.cs +++ b/Jint/Native/BigInt/BigIntConstructor.cs @@ -1,4 +1,4 @@ -using System.Numerics; +using System.Numerics; using Jint.Collections; using Jint.Native.Function; using Jint.Native.Object; @@ -115,9 +115,9 @@ ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) var o = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.BigInt.PrototypeObject, - static (engine, realm, state) => new BigIntInstance(engine, state), + static (engine, realm, state) => new BigIntInstance(engine, state!), value); - + return o; } @@ -125,10 +125,9 @@ ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) public BigIntInstance Construct(JsBigInt value) { - var instance = new BigIntInstance(Engine) + var instance = new BigIntInstance(Engine, value) { - _prototype = PrototypeObject, - BigIntData = value + _prototype = PrototypeObject }; return instance; diff --git a/Jint/Native/BigInt/BigIntInstance.cs b/Jint/Native/BigInt/BigIntInstance.cs index a4feeceb43..d14b5d0ffd 100644 --- a/Jint/Native/BigInt/BigIntInstance.cs +++ b/Jint/Native/BigInt/BigIntInstance.cs @@ -1,17 +1,12 @@ -using Jint.Native.Object; +using Jint.Native.Object; using Jint.Runtime; namespace Jint.Native.BigInt; public sealed class BigIntInstance : ObjectInstance, IPrimitiveInstance { - public BigIntInstance(Engine engine) - : base(engine, ObjectClass.Object) - { - } - public BigIntInstance(Engine engine, JsBigInt value) - : this(engine) + : base(engine, ObjectClass.Object) { BigIntData = value; } @@ -20,5 +15,5 @@ public BigIntInstance(Engine engine, JsBigInt value) JsValue IPrimitiveInstance.PrimitiveValue => BigIntData; - public JsBigInt BigIntData { get; internal init; } -} \ No newline at end of file + public JsBigInt BigIntData { get; } +} diff --git a/Jint/Native/BigInt/BigIntPrototype.cs b/Jint/Native/BigInt/BigIntPrototype.cs index bb167bef65..b0fc9edd5c 100644 --- a/Jint/Native/BigInt/BigIntPrototype.cs +++ b/Jint/Native/BigInt/BigIntPrototype.cs @@ -1,4 +1,4 @@ -using System.Numerics; +using System.Numerics; using Jint.Collections; using Jint.Native.Object; using Jint.Native.Symbol; diff --git a/Jint/Native/Boolean/BooleanConstructor.cs b/Jint/Native/Boolean/BooleanConstructor.cs index aace548577..90f3841897 100644 --- a/Jint/Native/Boolean/BooleanConstructor.cs +++ b/Jint/Native/Boolean/BooleanConstructor.cs @@ -1,4 +1,4 @@ -using Jint.Native.Function; +using Jint.Native.Function; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -51,16 +51,15 @@ ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) var o = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.Boolean.PrototypeObject, - static (engine, realm, state) => new BooleanInstance(engine, (JsBoolean) state), b); + static (engine, realm, state) => new BooleanInstance(engine, (JsBoolean) state!), b); return o; } public BooleanInstance Construct(JsBoolean value) { - var instance = new BooleanInstance(Engine) + var instance = new BooleanInstance(Engine, value) { - _prototype = PrototypeObject, - BooleanData = value, + _prototype = PrototypeObject }; return instance; diff --git a/Jint/Native/Boolean/BooleanInstance.cs b/Jint/Native/Boolean/BooleanInstance.cs index 061af4d0d7..808f89fa74 100644 --- a/Jint/Native/Boolean/BooleanInstance.cs +++ b/Jint/Native/Boolean/BooleanInstance.cs @@ -1,15 +1,10 @@ -using Jint.Native.Object; +using Jint.Native.Object; using Jint.Runtime; namespace Jint.Native.Boolean { public class BooleanInstance : ObjectInstance, IPrimitiveInstance { - public BooleanInstance(Engine engine) - : base(engine, ObjectClass.Boolean) - { - } - public BooleanInstance(Engine engine, JsBoolean value) : base(engine, ObjectClass.Boolean) { @@ -20,6 +15,6 @@ public BooleanInstance(Engine engine, JsBoolean value) JsValue IPrimitiveInstance.PrimitiveValue => BooleanData; - public JsValue BooleanData { get; internal init; } + public JsValue BooleanData { get; } } -} \ No newline at end of file +} diff --git a/Jint/Native/Boolean/BooleanPrototype.cs b/Jint/Native/Boolean/BooleanPrototype.cs index 758997dc39..96c83eb41e 100644 --- a/Jint/Native/Boolean/BooleanPrototype.cs +++ b/Jint/Native/Boolean/BooleanPrototype.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -18,10 +18,9 @@ internal BooleanPrototype( Engine engine, Realm realm, BooleanConstructor constructor, - ObjectPrototype objectPrototype) : base(engine) + ObjectPrototype objectPrototype) : base(engine, JsBoolean.False) { _prototype = objectPrototype; - BooleanData = JsBoolean.False; _realm = realm; _constructor = constructor; } @@ -59,4 +58,4 @@ private JsValue ToBooleanString(JsValue thisObj, JsValue[] arguments) return ((JsBoolean) b)._value ? JsString.TrueString : JsString.FalseString; } } -} \ No newline at end of file +} diff --git a/Jint/Native/DataView/DataViewConstructor.cs b/Jint/Native/DataView/DataViewConstructor.cs index 4c11f6ce69..d1e0c1ffc4 100644 --- a/Jint/Native/DataView/DataViewConstructor.cs +++ b/Jint/Native/DataView/DataViewConstructor.cs @@ -80,7 +80,7 @@ ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) var o = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.DataView.PrototypeObject, - static (Engine engine, Realm _, object _) => new DataViewInstance(engine)); + static (Engine engine, Realm _, object? _) => new DataViewInstance(engine)); if (buffer.IsDetachedBuffer) { diff --git a/Jint/Native/DataView/DataViewInstance.cs b/Jint/Native/DataView/DataViewInstance.cs index 0f1390c1f3..c1eb32ff1a 100644 --- a/Jint/Native/DataView/DataViewInstance.cs +++ b/Jint/Native/DataView/DataViewInstance.cs @@ -8,7 +8,7 @@ namespace Jint.Native.DataView /// public sealed class DataViewInstance : ObjectInstance { - internal ArrayBufferInstance _viewedArrayBuffer; + internal ArrayBufferInstance? _viewedArrayBuffer; internal uint _byteLength; internal uint _byteOffset; @@ -16,4 +16,4 @@ internal DataViewInstance(Engine engine) : base(engine) { } } -} \ No newline at end of file +} diff --git a/Jint/Native/DataView/DataViewPrototype.cs b/Jint/Native/DataView/DataViewPrototype.cs index a1ccbcacd6..36166fcc48 100644 --- a/Jint/Native/DataView/DataViewPrototype.cs +++ b/Jint/Native/DataView/DataViewPrototype.cs @@ -79,7 +79,7 @@ private JsValue Buffer(JsValue thisObj, JsValue[] arguments) ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.buffer called on incompatible receiver " + thisObj); } - return o._viewedArrayBuffer; + return o._viewedArrayBuffer!; } /// @@ -93,7 +93,7 @@ private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.byteLength called on incompatible receiver " + thisObj); } - var buffer = o._viewedArrayBuffer; + var buffer = o._viewedArrayBuffer!; buffer.AssertNotDetached(); return JsNumber.Create(o._byteLength); @@ -110,7 +110,7 @@ private JsValue ByteOffset(JsValue thisObj, JsValue[] arguments) ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.byteOffset called on incompatible receiver " + thisObj); } - var buffer = o._viewedArrayBuffer; + var buffer = o._viewedArrayBuffer!; buffer.AssertNotDetached(); return JsNumber.Create(o._byteOffset); @@ -233,7 +233,7 @@ private JsValue GetViewValue( var getIndex = (int) TypeConverter.ToIndex(_realm, requestIndex); var isLittleEndianBoolean = TypeConverter.ToBoolean(isLittleEndian); - var buffer = dataView._viewedArrayBuffer; + var buffer = dataView._viewedArrayBuffer!; buffer.AssertNotDetached(); @@ -278,7 +278,7 @@ private JsValue SetViewValue( } var isLittleEndianBoolean = TypeConverter.ToBoolean(isLittleEndian); - var buffer = dataView._viewedArrayBuffer; + var buffer = dataView._viewedArrayBuffer!; buffer.AssertNotDetached(); var viewOffset = dataView._byteOffset; @@ -294,4 +294,4 @@ private JsValue SetViewValue( return Undefined; } } -} \ No newline at end of file +} diff --git a/Jint/Native/Date/DateConstructor.cs b/Jint/Native/Date/DateConstructor.cs index e73dcfbb6b..ac80e58a04 100644 --- a/Jint/Native/Date/DateConstructor.cs +++ b/Jint/Native/Date/DateConstructor.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using Jint.Collections; using Jint.Native.Function; using Jint.Native.Object; @@ -211,7 +211,7 @@ private ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) var o = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.Date.PrototypeObject, - static (Engine engine, Realm _, object _) => new DateInstance(engine)); + static (Engine engine, Realm _, object? _) => new DateInstance(engine)); o.DateValue = dv; return o; } diff --git a/Jint/Native/Date/DateInstance.cs b/Jint/Native/Date/DateInstance.cs index 1adb647978..6cb7853e1d 100644 --- a/Jint/Native/Date/DateInstance.cs +++ b/Jint/Native/Date/DateInstance.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using Jint.Native.Object; using Jint.Runtime; diff --git a/Jint/Native/Date/DatePrototype.cs b/Jint/Native/Date/DatePrototype.cs index 4c955a4aaa..9982582f1b 100644 --- a/Jint/Native/Date/DatePrototype.cs +++ b/Jint/Native/Date/DatePrototype.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using System.Runtime.CompilerServices; using Jint.Collections; using Jint.Native.Object; diff --git a/Jint/Native/Error/ErrorConstructor.cs b/Jint/Native/Error/ErrorConstructor.cs index 05f713532e..4054409470 100644 --- a/Jint/Native/Error/ErrorConstructor.cs +++ b/Jint/Native/Error/ErrorConstructor.cs @@ -1,4 +1,4 @@ -using Jint.Native.Function; +using Jint.Native.Function; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -46,7 +46,7 @@ private ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) var o = OrdinaryCreateFromConstructor( newTarget, _intrinsicDefaultProto, - static (Engine engine, Realm _, object _) => new ErrorInstance(engine)); + static (Engine engine, Realm _, object? _) => new ErrorInstance(engine)); var jsValue = arguments.At(0); if (!jsValue.IsUndefined()) diff --git a/Jint/Native/Error/ErrorInstance.cs b/Jint/Native/Error/ErrorInstance.cs index 9d69164e0f..2c3a4b3259 100644 --- a/Jint/Native/Error/ErrorInstance.cs +++ b/Jint/Native/Error/ErrorInstance.cs @@ -1,5 +1,3 @@ -#nullable enable - using Jint.Native.Object; using Jint.Runtime; diff --git a/Jint/Native/Error/ErrorPrototype.cs b/Jint/Native/Error/ErrorPrototype.cs index 6930c6c5f6..c1a180877e 100644 --- a/Jint/Native/Error/ErrorPrototype.cs +++ b/Jint/Native/Error/ErrorPrototype.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; diff --git a/Jint/Native/Function/BindFunctionInstance.cs b/Jint/Native/Function/BindFunctionInstance.cs index 80b8c00923..40b46e7658 100644 --- a/Jint/Native/Function/BindFunctionInstance.cs +++ b/Jint/Native/Function/BindFunctionInstance.cs @@ -1,4 +1,4 @@ -using Jint.Native.Object; +using Jint.Native.Object; using Jint.Runtime; namespace Jint.Native.Function @@ -12,7 +12,7 @@ internal sealed class BindFunctionInstance : ObjectInstance, IConstructor, ICall public BindFunctionInstance(Engine engine, Realm realm, - ObjectInstance proto, + ObjectInstance? proto, ObjectInstance targetFunction, JsValue boundThis, JsValue[] boundArgs) diff --git a/Jint/Native/Function/ClassDefinition.cs b/Jint/Native/Function/ClassDefinition.cs index 0f632ef99e..423c67a19c 100644 --- a/Jint/Native/Function/ClassDefinition.cs +++ b/Jint/Native/Function/ClassDefinition.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima; using Esprima.Ast; using Jint.Native.Object; diff --git a/Jint/Native/Function/ConstructorKind.cs b/Jint/Native/Function/ConstructorKind.cs index 088a4a274f..0b66cab2fe 100644 --- a/Jint/Native/Function/ConstructorKind.cs +++ b/Jint/Native/Function/ConstructorKind.cs @@ -5,4 +5,4 @@ internal enum ConstructorKind Base, Derived } -} \ No newline at end of file +} diff --git a/Jint/Native/Function/EvalFunctionInstance.cs b/Jint/Native/Function/EvalFunctionInstance.cs index 6a0cb38296..4790007e80 100644 --- a/Jint/Native/Function/EvalFunctionInstance.cs +++ b/Jint/Native/Function/EvalFunctionInstance.cs @@ -1,4 +1,4 @@ -using Esprima; +using Esprima; using Esprima.Ast; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -67,7 +67,7 @@ public JsValue PerformEval(JsValue x, Realm callerRealm, bool strictCaller, bool } var parser = new JavaScriptParser(x.ToString(), ParserOptions); - Script script = null; + Script? script = null; try { script = parser.ParseScript(strictCaller); @@ -76,7 +76,7 @@ public JsValue PerformEval(JsValue x, Realm callerRealm, bool strictCaller, bool { if (e.Description == Messages.InvalidLHSInAssignment) { - ExceptionHelper.ThrowReferenceError(callerRealm, (string) null); + ExceptionHelper.ThrowReferenceError(callerRealm, (string?) null); } else { @@ -110,7 +110,7 @@ public JsValue PerformEval(JsValue x, Realm callerRealm, bool strictCaller, bool { EnvironmentRecord lexEnv; EnvironmentRecord varEnv; - PrivateEnvironmentRecord privateEnv; + PrivateEnvironmentRecord? privateEnv; if (direct) { lexEnv = JintEnvironment.NewDeclarativeEnvironment(_engine, ctx.LexicalEnvironment); @@ -138,7 +138,7 @@ public JsValue PerformEval(JsValue x, Realm callerRealm, bool strictCaller, bool Engine.EvalDeclarationInstantiation(script, varEnv, lexEnv, privateEnv, strictEval); var statement = new JintScript(script); - var result = statement.Execute(_engine._activeEvaluationContext); + var result = statement.Execute(_engine._activeEvaluationContext!); var value = result.GetValueOrDefault(); if (result.Type == CompletionType.Throw) diff --git a/Jint/Native/Function/FunctionConstructor.cs b/Jint/Native/Function/FunctionConstructor.cs index 3e593d3f65..b8fc6db9ec 100644 --- a/Jint/Native/Function/FunctionConstructor.cs +++ b/Jint/Native/Function/FunctionConstructor.cs @@ -1,4 +1,4 @@ -using Esprima; +using Esprima; using Esprima.Ast; using Jint.Native.Object; using Jint.Runtime; @@ -70,7 +70,7 @@ internal FunctionInstance CreateDynamicFunction( newTarget = constructor; } - Func fallbackProto = null; + Func? fallbackProto = null; switch (kind) { case FunctionKind.Normal: @@ -105,10 +105,10 @@ internal FunctionInstance CreateDynamicFunction( body = TypeConverter.ToString(args[argCount - 1]); } - IFunction function = null; + IFunction? function = null; try { - string functionExpression = null; + string? functionExpression = null; if (argCount == 0) { switch (kind) @@ -185,7 +185,7 @@ internal FunctionInstance CreateDynamicFunction( var proto = GetPrototypeFromConstructor(newTarget, fallbackProto); var realmF = _realm; var scope = realmF.GlobalEnv; - PrivateEnvironmentRecord privateScope = null; + PrivateEnvironmentRecord? privateScope = null; var definition = new JintFunctionDefinition(_engine, function); FunctionInstance F = OrdinaryFunctionCreate(proto, definition, function.Strict ? FunctionThisMode.Strict : FunctionThisMode.Global, scope, privateScope); @@ -218,7 +218,7 @@ internal ScriptFunctionInstance OrdinaryFunctionCreate( JintFunctionDefinition function, FunctionThisMode thisMode, EnvironmentRecord scope, - PrivateEnvironmentRecord privateScope) + PrivateEnvironmentRecord? privateScope) { return new ScriptFunctionInstance( _engine, @@ -238,7 +238,7 @@ internal ScriptFunctionInstance OrdinaryFunctionCreate( internal FunctionInstance InstantiateFunctionObject( JintFunctionDefinition functionDeclaration, EnvironmentRecord scope, - PrivateEnvironmentRecord privateScope) + PrivateEnvironmentRecord? privateScope) { return !functionDeclaration.Function.Generator ? InstantiateOrdinaryFunctionObject(functionDeclaration, scope, privateScope) @@ -251,7 +251,7 @@ internal FunctionInstance InstantiateFunctionObject( private FunctionInstance InstantiateOrdinaryFunctionObject( JintFunctionDefinition functionDeclaration, EnvironmentRecord scope, - PrivateEnvironmentRecord privateScope) + PrivateEnvironmentRecord? privateScope) { var F = OrdinaryFunctionCreate( _realm.Intrinsics.Function.PrototypeObject, @@ -272,7 +272,7 @@ private FunctionInstance InstantiateOrdinaryFunctionObject( private FunctionInstance InstantiateGeneratorFunctionObject( JintFunctionDefinition functionDeclaration, EnvironmentRecord scope, - PrivateEnvironmentRecord privateScope) + PrivateEnvironmentRecord? privateScope) { // TODO generators return InstantiateOrdinaryFunctionObject(functionDeclaration, scope, privateScope); diff --git a/Jint/Native/Function/FunctionInstance.cs b/Jint/Native/Function/FunctionInstance.cs index ab17114d37..2033030cfd 100644 --- a/Jint/Native/Function/FunctionInstance.cs +++ b/Jint/Native/Function/FunctionInstance.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using Esprima.Ast; using Jint.Native.Object; using Jint.Native.Proxy; @@ -11,25 +11,25 @@ namespace Jint.Native.Function { public abstract class FunctionInstance : ObjectInstance, ICallable { - protected PropertyDescriptor _prototypeDescriptor; + protected PropertyDescriptor? _prototypeDescriptor; - protected internal PropertyDescriptor _length; - internal PropertyDescriptor _nameDescriptor; + protected internal PropertyDescriptor? _length; + internal PropertyDescriptor? _nameDescriptor; - protected internal EnvironmentRecord _environment; - internal readonly JintFunctionDefinition _functionDefinition; + protected internal EnvironmentRecord? _environment; + internal readonly JintFunctionDefinition _functionDefinition = null!; internal readonly FunctionThisMode _thisMode; internal JsValue _homeObject = Undefined; internal ConstructorKind _constructorKind = ConstructorKind.Base; internal Realm _realm; - internal PrivateEnvironmentRecord _privateEnvironment; - private readonly IScriptOrModule _scriptOrModule; + internal PrivateEnvironmentRecord? _privateEnvironment; + private readonly IScriptOrModule? _scriptOrModule; protected FunctionInstance( Engine engine, Realm realm, - JsString name) + JsString? name) : this(engine, realm, name, FunctionThisMode.Global, ObjectClass.Function) { } @@ -43,7 +43,7 @@ internal FunctionInstance( : this( engine, realm, - !string.IsNullOrWhiteSpace(function.Name) ? new JsString(function.Name) : null, + !string.IsNullOrWhiteSpace(function.Name) ? new JsString(function.Name!) : null, thisMode) { _functionDefinition = function; @@ -53,7 +53,7 @@ internal FunctionInstance( internal FunctionInstance( Engine engine, Realm realm, - JsString name, + JsString? name, FunctionThisMode thisMode = FunctionThisMode.Global, ObjectClass objectClass = ObjectClass.Function) : base(engine, objectClass) @@ -181,7 +181,7 @@ public override void RemoveOwnProperty(JsValue property) /// /// https://tc39.es/ecma262/#sec-setfunctionname /// - internal void SetFunctionName(JsValue name, string prefix = null, bool force = false) + internal void SetFunctionName(JsValue name, string? prefix = null, bool force = false) { if (!force && _nameDescriptor != null && UnwrapJsValue(_nameDescriptor) != JsString.Empty) { @@ -213,8 +213,8 @@ internal void SetFunctionName(JsValue name, string prefix = null, bool force = f internal T OrdinaryCreateFromConstructor( JsValue constructor, Func intrinsicDefaultProto, - Func objectCreator, - TState state = default) where T : ObjectInstance + Func objectCreator, + TState? state = default) where T : ObjectInstance { var proto = GetPrototypeFromConstructor(constructor, intrinsicDefaultProto); @@ -229,8 +229,7 @@ internal T OrdinaryCreateFromConstructor( [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ObjectInstance GetPrototypeFromConstructor(JsValue constructor, Func intrinsicDefaultProto) { - var proto = constructor.Get(CommonProperties.Prototype, constructor) as ObjectInstance; - if (proto is null) + if (constructor.Get(CommonProperties.Prototype, constructor) is not ObjectInstance proto) { var realm = GetFunctionRealm(constructor); proto = intrinsicDefaultProto(realm.Intrinsics); @@ -354,7 +353,7 @@ internal ExecutionContext PrepareForOrdinaryCall(JsValue newTarget) return _engine.EnterExecutionContext(calleeContext); } - internal void MakeConstructor(bool writableProperty = true, ObjectInstance prototype = null) + internal void MakeConstructor(bool writableProperty = true, ObjectInstance? prototype = null) { _constructorKind = ConstructorKind.Base; if (prototype is null) @@ -387,7 +386,7 @@ public override string ToString() private sealed class ObjectInstanceWithConstructor : ObjectInstance { - private PropertyDescriptor _constructor; + private PropertyDescriptor? _constructor; public ObjectInstanceWithConstructor(Engine engine, ObjectInstance thisObj) : base(engine) { diff --git a/Jint/Native/Function/FunctionKind.cs b/Jint/Native/Function/FunctionKind.cs index dbc0d57255..bcb1fdfd72 100644 --- a/Jint/Native/Function/FunctionKind.cs +++ b/Jint/Native/Function/FunctionKind.cs @@ -7,4 +7,4 @@ internal enum FunctionKind Generator, AsyncGenerator } -} \ No newline at end of file +} diff --git a/Jint/Native/Function/FunctionPrototype.cs b/Jint/Native/Function/FunctionPrototype.cs index 7f803102ce..b62881cc5d 100644 --- a/Jint/Native/Function/FunctionPrototype.cs +++ b/Jint/Native/Function/FunctionPrototype.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Array; using Jint.Native.Object; using Jint.Native.Symbol; diff --git a/Jint/Native/Function/FunctionThisMode.cs b/Jint/Native/Function/FunctionThisMode.cs index 9f22766a45..ed5371f7ea 100644 --- a/Jint/Native/Function/FunctionThisMode.cs +++ b/Jint/Native/Function/FunctionThisMode.cs @@ -6,4 +6,4 @@ internal enum FunctionThisMode Strict, Global } -} \ No newline at end of file +} diff --git a/Jint/Native/Function/ScriptFunctionInstance.cs b/Jint/Native/Function/ScriptFunctionInstance.cs index e62f21f4f4..d9c2afcba2 100644 --- a/Jint/Native/Function/ScriptFunctionInstance.cs +++ b/Jint/Native/Function/ScriptFunctionInstance.cs @@ -1,4 +1,4 @@ -using Esprima.Ast; +using Esprima.Ast; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -20,7 +20,7 @@ public ScriptFunctionInstance( IFunction functionDeclaration, EnvironmentRecord scope, bool strict, - ObjectInstance proto = null) + ObjectInstance? proto = null) : this( engine, new JintFunctionDefinition(engine, functionDeclaration), @@ -35,7 +35,7 @@ internal ScriptFunctionInstance( JintFunctionDefinition function, EnvironmentRecord scope, FunctionThisMode thisMode, - ObjectInstance proto = null) + ObjectInstance? proto = null) : base(engine, engine.Realm, function, scope, thisMode) { _prototype = proto ?? _engine.Realm.Intrinsics.Function.PrototypeObject; @@ -107,7 +107,7 @@ protected internal override JsValue Call(JsValue thisArgument, JsValue[] argumen internal override bool IsConstructor => (_homeObject.IsUndefined() || _isClassConstructor) && _functionDefinition?.Function is not ArrowFunctionExpression - && _functionDefinition?.Function.Generator != true; + && _functionDefinition?.Function?.Generator != true; /// /// https://tc39.es/ecma262/#sec-ecmascript-function-objects-construct-argumentslist-newtarget @@ -124,7 +124,7 @@ ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) thisArgument = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.Object.PrototypeObject, - static (Engine engine, Realm _, object _) => new ObjectInstance(engine)); + static (Engine engine, Realm _, object? _) => new ObjectInstance(engine)); } var calleeContext = PrepareForOrdinaryCall(newTarget); diff --git a/Jint/Native/Function/ThrowTypeError.cs b/Jint/Native/Function/ThrowTypeError.cs index 40936eda14..879900f371 100644 --- a/Jint/Native/Function/ThrowTypeError.cs +++ b/Jint/Native/Function/ThrowTypeError.cs @@ -1,4 +1,4 @@ -using Jint.Runtime; +using Jint.Runtime; using Jint.Runtime.Descriptors; namespace Jint.Native.Function diff --git a/Jint/Native/Generator/GeneratorKind.cs b/Jint/Native/Generator/GeneratorKind.cs index 9c8abf9e4c..7f79d8cf58 100644 --- a/Jint/Native/Generator/GeneratorKind.cs +++ b/Jint/Native/Generator/GeneratorKind.cs @@ -6,4 +6,4 @@ internal enum GeneratorKind Sync, Async } -} \ No newline at end of file +} diff --git a/Jint/Native/Global/GlobalObject.cs b/Jint/Native/Global/GlobalObject.cs index 142e109ef9..90e33a366c 100644 --- a/Jint/Native/Global/GlobalObject.cs +++ b/Jint/Native/Global/GlobalObject.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using System.Runtime.CompilerServices; using System.Text; using Jint.Collections; @@ -32,98 +32,98 @@ protected override void Initialize() var properties = new PropertyDictionary(55, checkExistingKeys: false) { - ["AggregateError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.AggregateError, propertyFlags), - ["Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Array, propertyFlags), - ["ArrayBuffer"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.ArrayBuffer, propertyFlags), + ["AggregateError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.AggregateError, propertyFlags), + ["Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Array, propertyFlags), + ["ArrayBuffer"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.ArrayBuffer, propertyFlags), ["Atomics"] = new LazyPropertyDescriptor(this, static state => Undefined, propertyFlags), - ["BigInt"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.BigInt, propertyFlags), - ["BigInt64Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.BigInt64Array, propertyFlags), - ["BigUint64Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.BigUint64Array, propertyFlags), - ["Boolean"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Boolean, propertyFlags), - ["DataView"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.DataView, propertyFlags), - ["Date"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Date, propertyFlags), - ["Error"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Error, propertyFlags), - ["EvalError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.EvalError, propertyFlags), + ["BigInt"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.BigInt, propertyFlags), + ["BigInt64Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.BigInt64Array, propertyFlags), + ["BigUint64Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.BigUint64Array, propertyFlags), + ["Boolean"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Boolean, propertyFlags), + ["DataView"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.DataView, propertyFlags), + ["Date"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Date, propertyFlags), + ["Error"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Error, propertyFlags), + ["EvalError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.EvalError, propertyFlags), ["FinalizationRegistry"] = new LazyPropertyDescriptor(this, static state => Undefined, propertyFlags), - ["Float32Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Float32Array, propertyFlags), - ["Float64Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Float64Array, propertyFlags), + ["Float32Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Float32Array, propertyFlags), + ["Float64Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Float64Array, propertyFlags), ["Function"] = new PropertyDescriptor(_realm.Intrinsics.Function, propertyFlags), - ["Int16Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Int16Array, propertyFlags), - ["Int32Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Int32Array, propertyFlags), - ["Int8Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Int8Array, propertyFlags), - ["JSON"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Json, propertyFlags), - ["Map"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Map, propertyFlags), - ["Math"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Math, propertyFlags), - ["Number"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Number, propertyFlags), + ["Int16Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Int16Array, propertyFlags), + ["Int32Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Int32Array, propertyFlags), + ["Int8Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Int8Array, propertyFlags), + ["JSON"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Json, propertyFlags), + ["Map"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Map, propertyFlags), + ["Math"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Math, propertyFlags), + ["Number"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Number, propertyFlags), ["Object"] = new PropertyDescriptor(_realm.Intrinsics.Object, propertyFlags), - ["Promise"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Promise, propertyFlags), - ["Proxy"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Proxy, propertyFlags), - ["RangeError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.RangeError, propertyFlags), - ["ReferenceError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.ReferenceError, propertyFlags), - ["Reflect"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Reflect, propertyFlags), - ["RegExp"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.RegExp, propertyFlags), - ["Set"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Set, propertyFlags), - ["ShadowRealm"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.ShadowRealm, propertyFlags), + ["Promise"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Promise, propertyFlags), + ["Proxy"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Proxy, propertyFlags), + ["RangeError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.RangeError, propertyFlags), + ["ReferenceError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.ReferenceError, propertyFlags), + ["Reflect"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Reflect, propertyFlags), + ["RegExp"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.RegExp, propertyFlags), + ["Set"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Set, propertyFlags), + ["ShadowRealm"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.ShadowRealm, propertyFlags), ["SharedArrayBuffer"] = new LazyPropertyDescriptor(this, static state => Undefined, propertyFlags), - ["String"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.String, propertyFlags), - ["Symbol"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Symbol, propertyFlags), - ["SyntaxError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.SyntaxError, propertyFlags), - ["TypeError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.TypeError, propertyFlags), - ["TypedArray"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.TypedArray, propertyFlags), - ["URIError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.UriError, propertyFlags), - ["Uint16Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Uint16Array, propertyFlags), - ["Uint32Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Uint32Array, propertyFlags), - ["Uint8Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Uint8Array, propertyFlags), - ["Uint8ClampedArray"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Uint8ClampedArray, propertyFlags), - ["WeakMap"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.WeakMap, propertyFlags), + ["String"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.String, propertyFlags), + ["Symbol"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Symbol, propertyFlags), + ["SyntaxError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.SyntaxError, propertyFlags), + ["TypeError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.TypeError, propertyFlags), + ["TypedArray"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.TypedArray, propertyFlags), + ["URIError"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.UriError, propertyFlags), + ["Uint16Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Uint16Array, propertyFlags), + ["Uint32Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Uint32Array, propertyFlags), + ["Uint8Array"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Uint8Array, propertyFlags), + ["Uint8ClampedArray"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Uint8ClampedArray, propertyFlags), + ["WeakMap"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.WeakMap, propertyFlags), ["WeakRef"] = new LazyPropertyDescriptor(this, static state => Undefined, propertyFlags), - ["WeakSet"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.WeakSet, propertyFlags), + ["WeakSet"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.WeakSet, propertyFlags), ["NaN"] = new PropertyDescriptor(double.NaN, PropertyFlag.AllForbidden), ["Infinity"] = new PropertyDescriptor(double.PositiveInfinity, PropertyFlag.AllForbidden), ["undefined"] = new PropertyDescriptor(Undefined, PropertyFlag.AllForbidden), - ["parseInt"] = new LazyPropertyDescriptor(this, static state => new ClrFunctionInstance(((GlobalObject) state)._engine, "parseInt", ParseInt, 2, lengthFlags), propertyFlags), - ["parseFloat"] = new LazyPropertyDescriptor(this, static state => new ClrFunctionInstance(((GlobalObject) state)._engine, "parseFloat", ParseFloat, 1, lengthFlags), propertyFlags), - ["isNaN"] = new LazyPropertyDescriptor(this, static state => new ClrFunctionInstance(((GlobalObject) state)._engine, "isNaN", IsNaN, 1, lengthFlags), propertyFlags), - ["isFinite"] = new LazyPropertyDescriptor(this, static state => new ClrFunctionInstance(((GlobalObject) state)._engine, "isFinite", IsFinite, 1, lengthFlags), propertyFlags), + ["parseInt"] = new LazyPropertyDescriptor(this, static state => new ClrFunctionInstance(((GlobalObject) state!)._engine, "parseInt", ParseInt, 2, lengthFlags), propertyFlags), + ["parseFloat"] = new LazyPropertyDescriptor(this, static state => new ClrFunctionInstance(((GlobalObject) state!)._engine, "parseFloat", ParseFloat, 1, lengthFlags), propertyFlags), + ["isNaN"] = new LazyPropertyDescriptor(this, static state => new ClrFunctionInstance(((GlobalObject) state!)._engine, "isNaN", IsNaN, 1, lengthFlags), propertyFlags), + ["isFinite"] = new LazyPropertyDescriptor(this, static state => new ClrFunctionInstance(((GlobalObject) state!)._engine, "isFinite", IsFinite, 1, lengthFlags), propertyFlags), ["decodeURI"] = new LazyPropertyDescriptor(this, static state => { - var global = (GlobalObject) state; + var global = (GlobalObject) state!; return new ClrFunctionInstance(global._engine, "decodeURI", global.DecodeUri, 1, lengthFlags); }, propertyFlags), ["decodeURIComponent"] = new LazyPropertyDescriptor(this, static state => { - var global = (GlobalObject) state; + var global = (GlobalObject) state!; return new ClrFunctionInstance(global._engine, "decodeURIComponent", global.DecodeUriComponent, 1, lengthFlags); }, propertyFlags), ["encodeURI"] = new LazyPropertyDescriptor(this, static state => { - var global = (GlobalObject) state; + var global = (GlobalObject) state!; return new ClrFunctionInstance(global._engine, "encodeURI", global.EncodeUri, 1, lengthFlags); }, propertyFlags), ["encodeURIComponent"] = new LazyPropertyDescriptor(this, static state => { - var global = (GlobalObject) state; + var global = (GlobalObject) state!; return new ClrFunctionInstance(global._engine, "encodeURIComponent", global.EncodeUriComponent, 1, lengthFlags); }, propertyFlags), ["escape"] = new LazyPropertyDescriptor(this, static state => { - var global = (GlobalObject) state; + var global = (GlobalObject) state!; return new ClrFunctionInstance(global._engine, "escape", global.Escape, 1, lengthFlags); }, propertyFlags), ["unescape"] = new LazyPropertyDescriptor(this, static state => { - var global = (GlobalObject) state; + var global = (GlobalObject) state!; return new ClrFunctionInstance(global._engine, "unescape", global.Unescape, 1, lengthFlags); }, propertyFlags), ["globalThis"] = new PropertyDescriptor(this, propertyFlags), - ["eval"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state)._realm.Intrinsics.Eval, PropertyFlag.Configurable | PropertyFlag.Writable), + ["eval"] = new LazyPropertyDescriptor(this, static state => ((GlobalObject) state!)._realm.Intrinsics.Eval, PropertyFlag.Configurable | PropertyFlag.Writable), // toString is not mentioned or actually required in spec, but some tests rely on it ["toString"] = new LazyPropertyDescriptor(this, static state => { - var global = (GlobalObject) state; + var global = (GlobalObject) state!; return new ClrFunctionInstance(global._engine, "toString", global.ToStringString, 1); }, propertyFlags) }; @@ -579,7 +579,7 @@ public JsValue DecodeUriComponent(JsValue thisObject, JsValue[] arguments) return Decode(componentString, null); } - private string Decode(string uriString, HashSet reservedSet) + private string Decode(string uriString, HashSet? reservedSet) { var strLen = uriString.Length; @@ -794,7 +794,7 @@ internal bool DefineOwnProperty(Key property, PropertyDescriptor desc) [MethodImpl(MethodImplOptions.AggressiveInlining)] internal PropertyDescriptor GetOwnProperty(Key property) { - Properties.TryGetValue(property, out var descriptor); + Properties!.TryGetValue(property, out var descriptor); return descriptor ?? PropertyDescriptor.Undefined; } @@ -803,7 +803,7 @@ internal bool Set(Key property, JsValue value) // here we are called only from global environment record context // we can take some shortcuts to be faster - if (!_properties.TryGetValue(property, out var existingDescriptor)) + if (!_properties!.TryGetValue(property, out var existingDescriptor)) { _properties[property] = new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable); return true; diff --git a/Jint/Native/ICallable.cs b/Jint/Native/ICallable.cs index ad17967da8..a5cd3473ed 100644 --- a/Jint/Native/ICallable.cs +++ b/Jint/Native/ICallable.cs @@ -1,4 +1,4 @@ -namespace Jint.Native +namespace Jint.Native { internal interface ICallable { diff --git a/Jint/Native/IConstructor.cs b/Jint/Native/IConstructor.cs index ce2d505376..f2d6f7f42a 100644 --- a/Jint/Native/IConstructor.cs +++ b/Jint/Native/IConstructor.cs @@ -1,4 +1,4 @@ -using Jint.Native.Object; +using Jint.Native.Object; namespace Jint.Native { diff --git a/Jint/Native/IPrimitiveInstance.cs b/Jint/Native/IPrimitiveInstance.cs index e48ad655a6..13da38adbb 100644 --- a/Jint/Native/IPrimitiveInstance.cs +++ b/Jint/Native/IPrimitiveInstance.cs @@ -1,4 +1,4 @@ -using Jint.Runtime; +using Jint.Runtime; namespace Jint.Native { diff --git a/Jint/Native/Iterator/ArrayIteratorType.cs b/Jint/Native/Iterator/ArrayIteratorType.cs index 55c634d6d1..64225090ee 100644 --- a/Jint/Native/Iterator/ArrayIteratorType.cs +++ b/Jint/Native/Iterator/ArrayIteratorType.cs @@ -6,4 +6,4 @@ internal enum ArrayIteratorType Value, KeyAndValue } -} \ No newline at end of file +} diff --git a/Jint/Native/Iterator/IteratorInstance.cs b/Jint/Native/Iterator/IteratorInstance.cs index 6fa2953bc8..5c64e689e6 100644 --- a/Jint/Native/Iterator/IteratorInstance.cs +++ b/Jint/Native/Iterator/IteratorInstance.cs @@ -29,7 +29,7 @@ public override object ToObject() return null; } - public override bool Equals(JsValue other) + public override bool Equals(JsValue? other) { return false; } @@ -62,14 +62,14 @@ internal sealed class KeyValueIteratorPosition : ObjectInstance { internal static ObjectInstance Done(Engine engine) => new KeyValueIteratorPosition(engine, null, null); - public KeyValueIteratorPosition(Engine engine, JsValue key, JsValue value) : base(engine) + public KeyValueIteratorPosition(Engine engine, JsValue? key, JsValue? value) : base(engine) { var done = ReferenceEquals(null, key) && ReferenceEquals(null, value); if (!done) { var arrayInstance = engine.Realm.Intrinsics.Array.ArrayCreate(2); - arrayInstance.SetIndexValue(0, key, false); - arrayInstance.SetIndexValue(1, value, false); + arrayInstance.SetIndexValue(0, key!, false); + arrayInstance.SetIndexValue(1, value!, false); SetProperty("value", new PropertyDescriptor(arrayInstance, PropertyFlag.AllForbidden)); } SetProperty("done", done ? PropertyDescriptor.AllForbiddenDescriptor.BooleanTrue : PropertyDescriptor.AllForbiddenDescriptor.BooleanFalse); @@ -78,7 +78,7 @@ public KeyValueIteratorPosition(Engine engine, JsValue key, JsValue value) : bas internal sealed class ValueIteratorPosition : ObjectInstance { - internal static ObjectInstance Done(Engine engine, JsValue value = null) + internal static ObjectInstance Done(Engine engine, JsValue? value = null) => new ValueIteratorPosition(engine, value ?? Undefined, true); public ValueIteratorPosition(Engine engine, JsValue value, bool? done = null) : base(engine) @@ -127,11 +127,12 @@ internal sealed class ObjectIterator : IteratorInstance public ObjectIterator(ObjectInstance target) : base(target.Engine) { _target = target; - _nextMethod = target.Get(CommonProperties.Next, target) as ICallable; - if (_nextMethod is null) + if (target.Get(CommonProperties.Next, target) is not ICallable callable) { ExceptionHelper.ThrowTypeError(target.Engine.Realm); + return; } + _nextMethod = callable; } public override bool TryIteratorStep(out ObjectInstance result) diff --git a/Jint/Native/Iterator/IteratorProtocol.cs b/Jint/Native/Iterator/IteratorProtocol.cs index 06bafe5fe2..0848cdf846 100644 --- a/Jint/Native/Iterator/IteratorProtocol.cs +++ b/Jint/Native/Iterator/IteratorProtocol.cs @@ -1,4 +1,4 @@ -using Jint.Native.Object; +using Jint.Native.Object; using Jint.Runtime; namespace Jint.Native.Iterator @@ -120,4 +120,4 @@ internal static void AddEntriesFromIterable(ObjectInstance target, IteratorInsta } } } -} \ No newline at end of file +} diff --git a/Jint/Native/Iterator/IteratorPrototype.cs b/Jint/Native/Iterator/IteratorPrototype.cs index e8047fc653..249d2c4144 100644 --- a/Jint/Native/Iterator/IteratorPrototype.cs +++ b/Jint/Native/Iterator/IteratorPrototype.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Symbol; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -11,12 +11,12 @@ namespace Jint.Native.Iterator /// internal class IteratorPrototype : Prototype { - private readonly string _name; + private readonly string? _name; internal IteratorPrototype( Engine engine, Realm realm, - string name, + string? name, Prototype objectPrototype) : base(engine, realm) { _prototype = objectPrototype; diff --git a/Jint/Native/Iterator/IteratorResult.cs b/Jint/Native/Iterator/IteratorResult.cs index 5b1ab3027b..a757584e7d 100644 --- a/Jint/Native/Iterator/IteratorResult.cs +++ b/Jint/Native/Iterator/IteratorResult.cs @@ -37,9 +37,9 @@ public override object ToObject() return this; } - public override bool Equals(JsValue other) + public override bool Equals(JsValue? other) { return ReferenceEquals(this, other); } } -} \ No newline at end of file +} diff --git a/Jint/Native/JsBigInt.cs b/Jint/Native/JsBigInt.cs index ca4a65f1f8..2f4be77503 100644 --- a/Jint/Native/JsBigInt.cs +++ b/Jint/Native/JsBigInt.cs @@ -101,12 +101,12 @@ public override bool Equals(object other) return Equals(other as JsBigInt); } - public override bool Equals(JsValue other) + public override bool Equals(JsValue? other) { return Equals(other as JsBigInt); } - public bool Equals(JsBigInt other) + public bool Equals(JsBigInt? other) { if (ReferenceEquals(null, other)) { diff --git a/Jint/Native/JsBoolean.cs b/Jint/Native/JsBoolean.cs index 823d838bac..6b5a8b178c 100644 --- a/Jint/Native/JsBoolean.cs +++ b/Jint/Native/JsBoolean.cs @@ -1,5 +1,3 @@ -#nullable enable - using Jint.Runtime; namespace Jint.Native @@ -39,7 +37,7 @@ public override bool IsLooselyEqual(JsValue value) return !value.IsNullOrUndefined() && base.IsLooselyEqual(value); } - public override bool Equals(JsValue obj) + public override bool Equals(JsValue? obj) { return Equals(obj as JsBoolean); } diff --git a/Jint/Native/JsNull.cs b/Jint/Native/JsNull.cs index 1272f2e968..312127e80c 100644 --- a/Jint/Native/JsNull.cs +++ b/Jint/Native/JsNull.cs @@ -1,5 +1,3 @@ -#nullable enable - using Jint.Runtime; namespace Jint.Native @@ -10,9 +8,9 @@ internal JsNull() : base(Types.Null) { } - public override object? ToObject() + public override object ToObject() { - return null; + return null!; } public override string ToString() @@ -25,7 +23,7 @@ public override bool IsLooselyEqual(JsValue value) return ReferenceEquals(Null, value) || ReferenceEquals(Undefined, value); } - public override bool Equals(JsValue obj) + public override bool Equals(JsValue? obj) { return Equals(obj as JsNull); } diff --git a/Jint/Native/JsNumber.cs b/Jint/Native/JsNumber.cs index c0b4e40e44..1b301b0237 100644 --- a/Jint/Native/JsNumber.cs +++ b/Jint/Native/JsNumber.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Numerics; using System.Runtime.CompilerServices; using Jint.Native.Number; @@ -263,7 +261,7 @@ public override bool IsLooselyEqual(JsValue value) return base.IsLooselyEqual(value); } - public override bool Equals(JsValue obj) + public override bool Equals(JsValue? obj) { return Equals(obj as JsNumber); } diff --git a/Jint/Native/JsString.cs b/Jint/Native/JsString.cs index e684cab064..ed044cc33d 100644 --- a/Jint/Native/JsString.cs +++ b/Jint/Native/JsString.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Text; using Jint.Native.Array; using Jint.Runtime; @@ -230,7 +228,7 @@ internal string Substring(int startIndex) return ToString().Substring(startIndex); } - public override bool Equals(JsValue obj) + public override bool Equals(JsValue? obj) { return Equals(obj as JsString); } @@ -336,7 +334,7 @@ internal override bool IsNullOrEmpty() public override object ToObject() => ToString(); - public override bool Equals(JsValue other) + public override bool Equals(JsValue? other) { if (other is ConcatenatedString cs) { diff --git a/Jint/Native/JsSymbol.cs b/Jint/Native/JsSymbol.cs index 98f842f08d..0f78789df9 100644 --- a/Jint/Native/JsSymbol.cs +++ b/Jint/Native/JsSymbol.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using Jint.Runtime; namespace Jint.Native @@ -33,12 +33,12 @@ public override string ToString() return "Symbol(" + value + ")"; } - public override bool Equals(JsValue obj) + public override bool Equals(JsValue? obj) { return Equals(obj as JsSymbol); } - public bool Equals(JsSymbol other) + public bool Equals(JsSymbol? other) { return ReferenceEquals(this, other); } diff --git a/Jint/Native/JsUndefined.cs b/Jint/Native/JsUndefined.cs index 5ac39b50e6..d215caccd0 100644 --- a/Jint/Native/JsUndefined.cs +++ b/Jint/Native/JsUndefined.cs @@ -1,4 +1,4 @@ -using Jint.Runtime; +using Jint.Runtime; namespace Jint.Native { @@ -10,7 +10,7 @@ internal JsUndefined() : base(Types.Undefined) public override object ToObject() { - return null; + return null!; } public override string ToString() @@ -23,12 +23,12 @@ public override bool IsLooselyEqual(JsValue value) return ReferenceEquals(Undefined, value) || ReferenceEquals(Null, value); } - public override bool Equals(JsValue obj) + public override bool Equals(JsValue? obj) { return Equals(obj as JsUndefined); } - public bool Equals(JsUndefined other) + public bool Equals(JsUndefined? other) { return !ReferenceEquals(null, other); } diff --git a/Jint/Native/JsValue.cs b/Jint/Native/JsValue.cs index cac1f3e97e..ee4c4df244 100644 --- a/Jint/Native/JsValue.cs +++ b/Jint/Native/JsValue.cs @@ -1,4 +1,5 @@ -using System.Diagnostics; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Numerics; using System.Runtime.CompilerServices; @@ -37,11 +38,12 @@ internal JsValue(InternalTypes type) [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal IteratorInstance GetIterator(Realm realm, GeneratorKind hint = GeneratorKind.Sync, ICallable method = null) + internal IteratorInstance GetIterator(Realm realm, GeneratorKind hint = GeneratorKind.Sync, ICallable? method = null) { if (!TryGetIterator(realm, out var iterator, hint, method)) { ExceptionHelper.ThrowTypeError(realm, "The value is not iterable"); + return null!; } return iterator; @@ -49,7 +51,7 @@ internal IteratorInstance GetIterator(Realm realm, GeneratorKind hint = Generato [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal bool TryGetIterator(Realm realm, out IteratorInstance iterator, GeneratorKind hint = GeneratorKind.Sync, ICallable method = null) + internal bool TryGetIterator(Realm realm, [NotNullWhen(true)] out IteratorInstance? iterator, GeneratorKind hint = GeneratorKind.Sync, ICallable? method = null) { var obj = TypeConverter.ToObject(realm, this); @@ -107,7 +109,7 @@ public Types Type /// /// Creates a valid instance from any instance /// - public static JsValue FromObject(Engine engine, object value) + public static JsValue FromObject(Engine engine, object? value) { if (value is null) { @@ -135,7 +137,7 @@ public static JsValue FromObject(Engine engine, object value) return defaultConversion; } - return null; + return null!; } /// @@ -209,7 +211,7 @@ public override string ToString() return "None"; } - public static bool operator ==(JsValue a, JsValue b) + public static bool operator ==(JsValue? a, JsValue? b) { if (a is null) { @@ -219,7 +221,7 @@ public override string ToString() return b is not null && a.Equals(b); } - public static bool operator !=(JsValue a, JsValue b) + public static bool operator !=(JsValue? a, JsValue? b) { return !(a == b); } @@ -265,14 +267,9 @@ public static implicit operator JsValue(bool value) } [DebuggerStepThrough] - public static implicit operator JsValue(string value) + public static implicit operator JsValue(string? value) { - if (value == null) - { - return Null; - } - - return JsString.Create(value); + return value == null ? Null : JsString.Create(value); } /// @@ -334,7 +331,7 @@ public override bool Equals(object obj) /// /// Strict equality. /// - public virtual bool Equals(JsValue other) + public virtual bool Equals(JsValue? other) { return ReferenceEquals(this, other); } @@ -416,7 +413,8 @@ internal virtual bool OrdinaryHasInstance(JsValue v) return false; } - if (v is not ObjectInstance o) + var o = v as ObjectInstance; + if (o is null) { return false; } diff --git a/Jint/Native/Json/JsonInstance.cs b/Jint/Native/Json/JsonInstance.cs index 12cc1f35e8..46a030c57c 100644 --- a/Jint/Native/Json/JsonInstance.cs +++ b/Jint/Native/Json/JsonInstance.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Object; using Jint.Native.Symbol; using Jint.Runtime; diff --git a/Jint/Native/Json/JsonParser.cs b/Jint/Native/Json/JsonParser.cs index e3cdd1563f..c8c7faedc8 100644 --- a/Jint/Native/Json/JsonParser.cs +++ b/Jint/Native/Json/JsonParser.cs @@ -15,15 +15,15 @@ public JsonParser(Engine engine) _engine = engine; } - private Extra _extra; + private Extra _extra = null!; private int _index; // position in the stream private int _length; // length of the stream private int _lineNumber; private int _lineStart; private Location _location; - private Token _lookahead; - private string _source; + private Token _lookahead = null!; + private string _source = null!; private State _state; @@ -152,7 +152,7 @@ private Token ScanPunctuator() } ThrowError(start, Messages.UnexpectedToken, code); - return null; + return null!; } private Token ScanNumericLiteral() @@ -259,7 +259,7 @@ private Token ScanBooleanLiteral() } ThrowError(start, Messages.UnexpectedToken, s); - return null; + return null!; } private Token ScanNullLiteral() @@ -286,7 +286,7 @@ private Token ScanNullLiteral() } ThrowError(start, Messages.UnexpectedToken, s); - return null; + return null!; } private Token ScanStringLiteral() @@ -465,7 +465,7 @@ private Token CollectToken() { var range = new[] {token.Range[0], token.Range[1]}; string value = _source.Slice(token.Range[0], token.Range[1]); - _extra.Tokens.Add(new Token + _extra!.Tokens.Add(new Token { Type = token.Type, Text = value, @@ -479,7 +479,7 @@ private Token CollectToken() private Token Lex() { - Token token = _lookahead; + Token token = _lookahead!; _index = token.Range[1]; _lineNumber = token.LineNumber.HasValue ? token.LineNumber.Value : 0; _lineStart = token.LineStart; @@ -659,7 +659,7 @@ public ObjectInstance ParseJsonObject() while (!Match("}")) { - Tokens type = _lookahead.Type; + Tokens type = _lookahead!.Type; if (type != Tokens.String) { ThrowUnexpected(Lex()); @@ -747,14 +747,14 @@ public JsValue Parse(string code) return Parse(code, null); } - public JsValue Parse(string code, ParserOptions options) + public JsValue Parse(string code, ParserOptions? options) { _source = code; _index = 0; _lineNumber = 1; _lineStart = 0; _length = _source.Length; - _lookahead = null; + _lookahead = null!; _state = new State { AllowIn = true, @@ -790,7 +790,7 @@ public JsValue Parse(string code, ParserOptions options) Peek(); - if(_lookahead.Type != Tokens.EOF) + if(_lookahead!.Type != Tokens.EOF) { ThrowError(_lookahead, Messages.UnexpectedToken, _lookahead.Text); } @@ -805,9 +805,9 @@ public JsValue Parse(string code, ParserOptions options) private sealed class Extra { public int? Loc; - public int[] Range; + public int[]? Range; - public List Tokens; + public List Tokens = null!; } private enum Tokens @@ -823,9 +823,9 @@ private enum Tokens class Token { public Tokens Type; - public object Value; - public string Text; - public int[] Range; + public object Value = null!; + public string Text = null!; + public int[] Range = null!; public int? LineNumber; public int LineStart; } diff --git a/Jint/Native/Json/JsonSerializer.cs b/Jint/Native/Json/JsonSerializer.cs index 14b9588cf0..6f3f9331e3 100644 --- a/Jint/Native/Json/JsonSerializer.cs +++ b/Jint/Native/Json/JsonSerializer.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Array; using Jint.Native.BigInt; using Jint.Native.Boolean; @@ -17,9 +17,10 @@ namespace Jint.Native.Json public class JsonSerializer { private readonly Engine _engine; - private ObjectTraverseStack _stack; - private string _indent, _gap; - private List _propertyList; + private ObjectTraverseStack _stack = null!; + private string? _indent; + private string? _gap; + private List? _propertyList; private JsValue _replacerFunction = Undefined.Instance; private static readonly JsString toJsonProperty = new("toJSON"); @@ -355,7 +356,7 @@ private string SerializeJSONObject(ObjectInstance value) var stepback = _indent; _indent += _gap; - var k = (IEnumerable) _propertyList ?? value.EnumerableOwnPropertyNames(ObjectInstance.EnumerableOwnPropertyNamesKind.Key); + var k = (IEnumerable?) _propertyList ?? value.EnumerableOwnPropertyNames(ObjectInstance.EnumerableOwnPropertyNamesKind.Key); var partial = new List(); foreach (var p in k) diff --git a/Jint/Native/Map/MapConstructor.cs b/Jint/Native/Map/MapConstructor.cs index 37efab99ec..e06047f182 100644 --- a/Jint/Native/Map/MapConstructor.cs +++ b/Jint/Native/Map/MapConstructor.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Function; using Jint.Native.Iterator; using Jint.Native.Object; @@ -61,8 +61,8 @@ ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) var map = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.Map.PrototypeObject, - static (Engine engine, Realm realm, object _) => new MapInstance(engine, realm)); - + static (Engine engine, Realm realm, object? _) => new MapInstance(engine, realm)); + if (arguments.Length > 0 && !arguments[0].IsNullOrUndefined()) { var adder = map.Get("set"); diff --git a/Jint/Native/Map/MapInstance.cs b/Jint/Native/Map/MapInstance.cs index 1d91f1b13d..3697746f22 100644 --- a/Jint/Native/Map/MapInstance.cs +++ b/Jint/Native/Map/MapInstance.cs @@ -1,4 +1,5 @@ -using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -26,7 +27,7 @@ public override PropertyDescriptor GetOwnProperty(JsValue property) return base.GetOwnProperty(property); } - protected override bool TryGetProperty(JsValue property, out PropertyDescriptor descriptor) + protected override bool TryGetProperty(JsValue property, [NotNullWhen(true)] out PropertyDescriptor? descriptor) { if (property == CommonProperties.Size) { diff --git a/Jint/Native/Map/MapIteratorPrototype.cs b/Jint/Native/Map/MapIteratorPrototype.cs index 323cc77153..3c2724a058 100644 --- a/Jint/Native/Map/MapIteratorPrototype.cs +++ b/Jint/Native/Map/MapIteratorPrototype.cs @@ -75,4 +75,4 @@ public override bool TryIteratorStep(out ObjectInstance nextItem) } } } -} \ No newline at end of file +} diff --git a/Jint/Native/Map/MapPrototype.cs b/Jint/Native/Map/MapPrototype.cs index 58ed0c68a7..23b3c1fcb0 100644 --- a/Jint/Native/Map/MapPrototype.cs +++ b/Jint/Native/Map/MapPrototype.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Object; using Jint.Native.Symbol; using Jint.Runtime; @@ -136,4 +136,4 @@ private MapInstance AssertMapInstance(JsValue thisObj) return map; } } -} \ No newline at end of file +} diff --git a/Jint/Native/Math/MathInstance.cs b/Jint/Native/Math/MathInstance.cs index 00d07953a6..ddbbceedd8 100644 --- a/Jint/Native/Math/MathInstance.cs +++ b/Jint/Native/Math/MathInstance.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Number; using Jint.Native.Object; using Jint.Native.Symbol; @@ -10,7 +10,7 @@ namespace Jint.Native.Math { public sealed class MathInstance : ObjectInstance { - private Random _random; + private Random? _random; internal MathInstance(Engine engine, ObjectPrototype objectPrototype) : base(engine) { diff --git a/Jint/Native/Null.cs b/Jint/Native/Null.cs index 11e1b4c8a2..a11f015bc9 100644 --- a/Jint/Native/Null.cs +++ b/Jint/Native/Null.cs @@ -1,8 +1,8 @@ -namespace Jint.Native +namespace Jint.Native { public static class Null { public static readonly JsValue Instance = JsValue.Null; public const string Text = "null"; } -} \ No newline at end of file +} diff --git a/Jint/Native/Number/Dtoa/Bignum.cs b/Jint/Native/Number/Dtoa/Bignum.cs index 65c8e92ed3..cddbd525e4 100644 --- a/Jint/Native/Number/Dtoa/Bignum.cs +++ b/Jint/Native/Number/Dtoa/Bignum.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Diagnostics; using Jint.Runtime; diff --git a/Jint/Native/Number/Dtoa/BignumDtoa.cs b/Jint/Native/Number/Dtoa/BignumDtoa.cs index 22d22d6ce0..098f4cedf9 100644 --- a/Jint/Native/Number/Dtoa/BignumDtoa.cs +++ b/Jint/Native/Number/Dtoa/BignumDtoa.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Diagnostics; using Jint.Runtime; diff --git a/Jint/Native/Number/Dtoa/CachePowers.cs b/Jint/Native/Number/Dtoa/CachePowers.cs index 88d008b18f..159708f567 100644 --- a/Jint/Native/Number/Dtoa/CachePowers.cs +++ b/Jint/Native/Number/Dtoa/CachePowers.cs @@ -1,4 +1,6 @@ -// Copyright 2010 the V8 project authors. All rights reserved. +#nullable disable + +// Copyright 2010 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: diff --git a/Jint/Native/Number/Dtoa/DiyFp.cs b/Jint/Native/Number/Dtoa/DiyFp.cs index ce42963531..27bc299de5 100644 --- a/Jint/Native/Number/Dtoa/DiyFp.cs +++ b/Jint/Native/Number/Dtoa/DiyFp.cs @@ -1,4 +1,6 @@ -// Copyright 2010 the V8 project authors. All rights reserved. +#nullable disable + +// Copyright 2010 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: diff --git a/Jint/Native/Number/Dtoa/DoubleHelper.cs b/Jint/Native/Number/Dtoa/DoubleHelper.cs index 84d1ce7c6f..91a4c2a48d 100644 --- a/Jint/Native/Number/Dtoa/DoubleHelper.cs +++ b/Jint/Native/Number/Dtoa/DoubleHelper.cs @@ -1,4 +1,6 @@ -// Copyright 2010 the V8 project authors. All rights reserved. +#nullable disable + +// Copyright 2010 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: diff --git a/Jint/Native/Number/Dtoa/DtoaBuilder.cs b/Jint/Native/Number/Dtoa/DtoaBuilder.cs index abacfdb236..07998053d0 100644 --- a/Jint/Native/Number/Dtoa/DtoaBuilder.cs +++ b/Jint/Native/Number/Dtoa/DtoaBuilder.cs @@ -1,4 +1,6 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +#nullable disable + +/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ diff --git a/Jint/Native/Number/Dtoa/DtoaMode.cs b/Jint/Native/Number/Dtoa/DtoaMode.cs index 94d703f3a8..52e9cde08d 100644 --- a/Jint/Native/Number/Dtoa/DtoaMode.cs +++ b/Jint/Native/Number/Dtoa/DtoaMode.cs @@ -1,3 +1,5 @@ +#nullable disable + namespace Jint.Native.Number.Dtoa { internal enum DtoaMode diff --git a/Jint/Native/Number/Dtoa/DtoaNumberFormatter.cs b/Jint/Native/Number/Dtoa/DtoaNumberFormatter.cs index d28604959b..06b9a2b07a 100644 --- a/Jint/Native/Number/Dtoa/DtoaNumberFormatter.cs +++ b/Jint/Native/Number/Dtoa/DtoaNumberFormatter.cs @@ -1,4 +1,6 @@ -using System.Diagnostics; +#nullable disable + +using System.Diagnostics; using Jint.Runtime; namespace Jint.Native.Number.Dtoa diff --git a/Jint/Native/Number/Dtoa/FastDtoa.cs b/Jint/Native/Number/Dtoa/FastDtoa.cs index b41ab0ca70..fed935103c 100644 --- a/Jint/Native/Number/Dtoa/FastDtoa.cs +++ b/Jint/Native/Number/Dtoa/FastDtoa.cs @@ -1,4 +1,6 @@ -// Copyright 2010 the V8 project authors. All rights reserved. +#nullable disable + +// Copyright 2010 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: diff --git a/Jint/Native/Number/Dtoa/NumberExtensions.cs b/Jint/Native/Number/Dtoa/NumberExtensions.cs index d2efbc8442..10c02a615d 100644 --- a/Jint/Native/Number/Dtoa/NumberExtensions.cs +++ b/Jint/Native/Number/Dtoa/NumberExtensions.cs @@ -1,4 +1,6 @@ -using System.Runtime.CompilerServices; +#nullable disable + +using System.Runtime.CompilerServices; namespace Jint.Native.Number.Dtoa { diff --git a/Jint/Native/Number/NumberConstructor.cs b/Jint/Native/Number/NumberConstructor.cs index f74af37e9f..ba41d43ac2 100644 --- a/Jint/Native/Number/NumberConstructor.cs +++ b/Jint/Native/Number/NumberConstructor.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Function; using Jint.Native.Global; using Jint.Native.Object; @@ -133,7 +133,7 @@ ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) var o = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.Number.PrototypeObject, - static (engine, realm, state) => new NumberInstance(engine, (JsNumber) state), n); + static (engine, realm, state) => new NumberInstance(engine, state!), n); return o; } @@ -156,14 +156,13 @@ private static JsNumber ProcessFirstParameter(JsValue[] arguments) return n; } - public NumberPrototype PrototypeObject { get; private set; } + public NumberPrototype PrototypeObject { get; } public NumberInstance Construct(JsNumber value) { - var instance = new NumberInstance(Engine) + var instance = new NumberInstance(Engine, value) { - _prototype = PrototypeObject, - NumberData = value + _prototype = PrototypeObject }; return instance; diff --git a/Jint/Native/Number/NumberInstance.cs b/Jint/Native/Number/NumberInstance.cs index 67fbf39e0e..4c5b31a903 100644 --- a/Jint/Native/Number/NumberInstance.cs +++ b/Jint/Native/Number/NumberInstance.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using Jint.Native.Object; using Jint.Runtime; @@ -8,11 +8,6 @@ public class NumberInstance : ObjectInstance, IPrimitiveInstance { private static readonly long NegativeZeroBits = BitConverter.DoubleToInt64Bits(-0.0); - public NumberInstance(Engine engine) - : base(engine, ObjectClass.Number) - { - } - public NumberInstance(Engine engine, JsNumber value) : base(engine, ObjectClass.Number) { @@ -23,7 +18,7 @@ public NumberInstance(Engine engine, JsNumber value) JsValue IPrimitiveInstance.PrimitiveValue => NumberData; - public JsNumber NumberData { get; internal init; } + public JsNumber NumberData { get; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNegativeZero(double x) diff --git a/Jint/Native/Number/NumberPrototype.cs b/Jint/Native/Number/NumberPrototype.cs index e4b37f0527..b049ce771a 100644 --- a/Jint/Native/Number/NumberPrototype.cs +++ b/Jint/Native/Number/NumberPrototype.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; using System.Globalization; using System.Text; using Jint.Collections; @@ -24,10 +24,9 @@ internal NumberPrototype( Realm realm, NumberConstructor constructor, ObjectPrototype objectPrototype) - : base(engine) + : base(engine, JsNumber.PositiveZero) { _prototype = objectPrototype; - NumberData = JsNumber.Create(0); _realm = realm; _constructor = constructor; } diff --git a/Jint/Native/Object/ObjectConstructor.cs b/Jint/Native/Object/ObjectConstructor.cs index d224cfe234..856e096884 100644 --- a/Jint/Native/Object/ObjectConstructor.cs +++ b/Jint/Native/Object/ObjectConstructor.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Function; using Jint.Native.Iterator; using Jint.Runtime; @@ -162,7 +162,7 @@ private ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) return OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.Object.PrototypeObject, - static (Engine engine, Realm _, object _) => new ObjectInstance(engine)); + static (Engine engine, Realm _, object? _) => new ObjectInstance(engine)); } if (arguments.Length > 0) @@ -174,7 +174,7 @@ private ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) } var type = value.Type; - if (type == Types.String || type == Types.Number || type == Types.Boolean) + if (type is Types.String or Types.Number or Types.Boolean) { return TypeConverter.ToObject(_realm, value); } diff --git a/Jint/Native/Object/ObjectInstance.cs b/Jint/Native/Object/ObjectInstance.cs index fcb8e21d50..fb98d9950d 100644 --- a/Jint/Native/Object/ObjectInstance.cs +++ b/Jint/Native/Object/ObjectInstance.cs @@ -1,4 +1,5 @@ -using System.Diagnostics; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Jint.Collections; using Jint.Native.Array; @@ -20,10 +21,10 @@ public class ObjectInstance : JsValue, IEquatable private bool _initialized; private readonly ObjectClass _class; - internal PropertyDictionary _properties; - internal SymbolDictionary _symbols; + internal PropertyDictionary? _properties; + internal SymbolDictionary? _symbols; - internal ObjectInstance _prototype; + internal ObjectInstance? _prototype; protected readonly Engine _engine; public ObjectInstance(Engine engine) : this(engine, ObjectClass.Object) @@ -52,7 +53,7 @@ public Engine Engine /// /// The prototype of this object. /// - public ObjectInstance Prototype + public ObjectInstance? Prototype { [DebuggerStepThrough] get => GetPrototypeOf(); @@ -64,7 +65,7 @@ public ObjectInstance Prototype /// public virtual bool Extensible { get; private set; } - internal PropertyDictionary Properties + internal PropertyDictionary? Properties { [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -86,7 +87,7 @@ internal ObjectClass Class /// /// https://tc39.es/ecma262/#sec-construct /// - internal static ObjectInstance Construct(IConstructor f, JsValue[] argumentsList = null, IConstructor newTarget = null) + internal static ObjectInstance Construct(IConstructor f, JsValue[]? argumentsList = null, IConstructor? newTarget = null) { newTarget ??= f; argumentsList ??= System.Array.Empty(); @@ -125,7 +126,7 @@ internal static IConstructor SpeciesConstructor(ObjectInstance o, IConstructor d return null; } - internal void SetProperties(PropertyDictionary properties) + internal void SetProperties(PropertyDictionary? properties) { if (properties != null) { @@ -134,7 +135,7 @@ internal void SetProperties(PropertyDictionary properties) _properties = properties; } - internal void SetSymbols(SymbolDictionary symbols) + internal void SetSymbols(SymbolDictionary? symbols) { _symbols = symbols; } @@ -227,7 +228,7 @@ public virtual List GetOwnPropertyKeys(Types types = Types.String | Typ } var keys = new List(_properties?.Count ?? 0 + _symbols?.Count ?? 0 + propertyKeys.Count); - List symbolKeys = null; + List? symbolKeys = null; if ((types & Types.String) != 0 && _properties != null) { @@ -274,7 +275,7 @@ protected virtual void AddProperty(JsValue property, PropertyDescriptor descript SetProperty(property, descriptor); } - protected virtual bool TryGetProperty(JsValue property, out PropertyDescriptor descriptor) + protected virtual bool TryGetProperty(JsValue property, [NotNullWhen(true)] out PropertyDescriptor? descriptor) { descriptor = null; @@ -366,7 +367,7 @@ public virtual PropertyDescriptor GetOwnProperty(JsValue property) { EnsureInitialized(); - PropertyDescriptor descriptor = null; + PropertyDescriptor? descriptor = null; var key = TypeConverter.ToPropertyKey(property); if (!key.IsSymbol()) { @@ -428,7 +429,7 @@ public bool TryGetValue(JsValue property, out JsValue value) } // if getter is not undefined it must be ICallable - var callable = getter.TryCast(); + var callable = (ICallable) getter; value = callable.Call(this, Arguments.Empty); return true; } @@ -662,7 +663,7 @@ public virtual bool DefineOwnProperty(JsValue property, PropertyDescriptor desc) /// /// https://tc39.es/ecma262/#sec-validateandapplypropertydescriptor /// - protected static bool ValidateAndApplyPropertyDescriptor(ObjectInstance o, JsValue property, bool extensible, PropertyDescriptor desc, PropertyDescriptor current) + protected static bool ValidateAndApplyPropertyDescriptor(ObjectInstance? o, JsValue property, bool extensible, PropertyDescriptor desc, PropertyDescriptor current) { var descValue = desc.Value; if (current == PropertyDescriptor.Undefined) @@ -792,7 +793,7 @@ protected static bool ValidateAndApplyPropertyDescriptor(ObjectInstance o, JsVal if (!current.Writable) { - if (!ReferenceEquals(descValue, null) && !SameValue(descValue, currentValue)) + if (!ReferenceEquals(descValue, null) && !SameValue(descValue, currentValue!)) { return false; } @@ -835,7 +836,7 @@ protected static bool ValidateAndApplyPropertyDescriptor(ObjectInstance o, JsVal current.Configurable = desc.Configurable; } - PropertyDescriptor mutable = null; + PropertyDescriptor? mutable = null; if (!ReferenceEquals(descGet, null)) { mutable = new GetSetPropertyDescriptor(mutable ?? current); @@ -906,7 +907,7 @@ private object ToObject(ObjectTraverseStack stack) } stack.Enter(this); - object converted = null; + object? converted = null; switch (Class) { case ObjectClass.String: @@ -959,11 +960,11 @@ private object ToObject(ObjectTraverseStack stack) if (this is ArrayInstance arrayInstance) { - var result = new object[arrayInstance.Length]; + var result = new object?[arrayInstance.Length]; for (uint i = 0; i < result.Length; i++) { var value = arrayInstance[i]; - object valueToSet = null; + object? valueToSet = null; if (!value.IsUndefined()) { valueToSet = value is ObjectInstance oi @@ -1000,7 +1001,7 @@ private object ToObject(ObjectTraverseStack stack) } stack.Exit(); - return converted; + return converted!; } /// @@ -1127,7 +1128,7 @@ public virtual bool PreventExtensions() return true; } - protected internal virtual ObjectInstance GetPrototypeOf() + protected internal virtual ObjectInstance? GetPrototypeOf() { return _prototype; } @@ -1185,7 +1186,7 @@ public virtual bool SetPrototypeOf(JsValue value) /// /// https://tc39.es/ecma262/#sec-setfunctionname /// - internal void SetFunctionName(JsValue name, string prefix = null) + internal void SetFunctionName(JsValue name, string? prefix = null) { if (name is JsSymbol symbol) { @@ -1243,12 +1244,12 @@ internal void CreateNonEnumerableDataPropertyOrThrow(JsValue p, JsValue v) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ICallable GetMethod(JsValue property) + internal ICallable? GetMethod(JsValue property) { return GetMethod(_engine.Realm, this, property); } - internal static ICallable GetMethod(Realm realm, JsValue v, JsValue p) + internal static ICallable? GetMethod(Realm realm, JsValue v, JsValue p) { var jsValue = v.Get(p); if (jsValue.IsNullOrUndefined()) @@ -1266,7 +1267,7 @@ internal static ICallable GetMethod(Realm realm, JsValue v, JsValue p) internal void CopyDataProperties( ObjectInstance target, - HashSet excludedItems) + HashSet? excludedItems) { var keys = GetOwnPropertyKeys(); for (var i = 0; i < keys.Count; i++) @@ -1344,7 +1345,7 @@ internal ObjectInstance AssertThisIsObjectInstance(JsValue value, string methodN { ThrowIncompatibleReceiver(value, methodName); } - return instance; + return instance!; } [MethodImpl(MethodImplOptions.NoInlining)] @@ -1353,12 +1354,12 @@ private void ThrowIncompatibleReceiver(JsValue value, string methodName) ExceptionHelper.ThrowTypeError(_engine.Realm, $"Method {methodName} called on incompatible receiver {value}"); } - public override bool Equals(JsValue obj) + public override bool Equals(JsValue? obj) { return Equals(obj as ObjectInstance); } - public bool Equals(ObjectInstance other) + public bool Equals(ObjectInstance? other) { if (other is null) { diff --git a/Jint/Native/Object/ObjectPrototype.cs b/Jint/Native/Object/ObjectPrototype.cs index 24314ce396..2db969fa85 100644 --- a/Jint/Native/Object/ObjectPrototype.cs +++ b/Jint/Native/Object/ObjectPrototype.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Array; using Jint.Native.Proxy; using Jint.Native.Symbol; diff --git a/Jint/Native/Promise/PromiseConstructor.cs b/Jint/Native/Promise/PromiseConstructor.cs index 42f8e4e0d1..3259be59cb 100644 --- a/Jint/Native/Promise/PromiseConstructor.cs +++ b/Jint/Native/Promise/PromiseConstructor.cs @@ -86,7 +86,7 @@ ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) var instance = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.Promise.PrototypeObject, - static (Engine engine, Realm _, object _) => new PromiseInstance(engine)); + static (Engine engine, Realm _, object? _) => new PromiseInstance(engine)); var (resolve, reject) = instance.CreateResolvingFunctions(); promiseExecutor.Call(Undefined, new JsValue[] {resolve, reject}); @@ -260,7 +260,7 @@ void ResolveIfFinished() // note that null here is important // it will help to detect if all inner promises were resolved // In F# it would be Option - results.Add(null); + results.Add(null!); var item = promiseResolve.Call(thisObj, new JsValue[] {value}); var thenProps = item.Get("then"); @@ -383,7 +383,7 @@ private JsValue Race(JsValue thisObj, JsValue[] arguments) // i. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »). - _engine.Invoke(nextPromise, "then", new[] {resolve as JsValue, rejectObj}); + _engine.Invoke(nextPromise, "then", new[] { (JsValue) resolve, rejectObj }); } while (true); } catch (JavaScriptException e) @@ -448,8 +448,8 @@ internal static PromiseCapability NewPromiseCapability(Engine engine, JsValue c) { var ctor = AssertConstructor(engine, c); - JsValue resolveArg = null; - JsValue rejectArg = null; + JsValue? resolveArg = null; + JsValue? rejectArg = null; JsValue Executor(JsValue thisObj, JsValue[] arguments) { @@ -474,8 +474,8 @@ JsValue Executor(JsValue thisObj, JsValue[] arguments) var instance = ctor.Construct(new JsValue[] {executor}, c); - ICallable resolve = null; - ICallable reject = null; + ICallable? resolve = null; + ICallable? reject = null; if (resolveArg is ICallable resFunc) { diff --git a/Jint/Native/Promise/PromiseInstance.cs b/Jint/Native/Promise/PromiseInstance.cs index 3a28f28444..07c51a66ad 100644 --- a/Jint/Native/Promise/PromiseInstance.cs +++ b/Jint/Native/Promise/PromiseInstance.cs @@ -44,7 +44,7 @@ internal sealed class PromiseInstance : ObjectInstance internal PromiseState State { get; private set; } // valid only in settled state (Fulfilled or Rejected) - internal JsValue Value { get; private set; } + internal JsValue Value { get; private set; } = null!; internal List PromiseRejectReactions = new(); internal List PromiseFulfillReactions = new(); diff --git a/Jint/Native/Promise/PromiseOperations.cs b/Jint/Native/Promise/PromiseOperations.cs index 3ecde27e2c..687ad8d3b2 100644 --- a/Jint/Native/Promise/PromiseOperations.cs +++ b/Jint/Native/Promise/PromiseOperations.cs @@ -1,5 +1,3 @@ -#nullable enable - using Jint.Native.Object; using Jint.Runtime; diff --git a/Jint/Native/Promise/PromisePrototype.cs b/Jint/Native/Promise/PromisePrototype.cs index fa14225a7f..a061e33166 100644 --- a/Jint/Native/Promise/PromisePrototype.cs +++ b/Jint/Native/Promise/PromisePrototype.cs @@ -64,7 +64,7 @@ private JsValue Then(JsValue thisValue, JsValue[] args) var ctor = SpeciesConstructor(promise, _realm.Intrinsics.Promise); // 4. Let resultCapability be ? NewPromiseCapability(C). - var capability = PromiseConstructor.NewPromiseCapability(_engine, ctor as JsValue); + var capability = PromiseConstructor.NewPromiseCapability(_engine, (JsValue) ctor); // 5. Return PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability). return PromiseOperations.PerformPromiseThen(_engine, promise, args.At(0), args.At(1), capability); @@ -127,7 +127,7 @@ private JsValue ThenFinallyFunctions(ICallable onFinally, IConstructor ctor) => var result = onFinally.Call(Undefined, Arguments.Empty); // 7. Let promise be ? PromiseResolve(C, result). - var promise = _realm.Intrinsics.Promise.Resolve(ctor as JsValue, new[] {result}); + var promise = _realm.Intrinsics.Promise.Resolve((JsValue) ctor, new[] {result}); // 8. Let valueThunk be equivalent to a function that returns value. var valueThunk = new ClrFunctionInstance(_engine, "", (_, _) => value); @@ -146,7 +146,7 @@ private JsValue CatchFinallyFunctions(ICallable onFinally, IConstructor ctor) => var result = onFinally.Call(Undefined, Arguments.Empty); // 7. Let promise be ? PromiseResolve(C, result). - var promise = _realm.Intrinsics.Promise.Resolve(ctor as JsValue, new[] {result}); + var promise = _realm.Intrinsics.Promise.Resolve((JsValue) ctor, new[] {result}); // 8. Let thrower be equivalent to a function that throws reason. var thrower = new ClrFunctionInstance(_engine, "", (_, _) => throw new JavaScriptException(reason)); @@ -155,4 +155,4 @@ private JsValue CatchFinallyFunctions(ICallable onFinally, IConstructor ctor) => return _engine.Invoke(promise, "then", new JsValue[] {thrower}); }, 1, PropertyFlag.Configurable); } -} \ No newline at end of file +} diff --git a/Jint/Native/Prototype.cs b/Jint/Native/Prototype.cs index 746a36e7c4..c5c3f07e77 100644 --- a/Jint/Native/Prototype.cs +++ b/Jint/Native/Prototype.cs @@ -12,4 +12,4 @@ protected Prototype(Engine engine, Realm realm) : base(engine) _realm = realm; } } -} \ No newline at end of file +} diff --git a/Jint/Native/Proxy/ProxyConstructor.cs b/Jint/Native/Proxy/ProxyConstructor.cs index a7d908823c..06d997bd17 100644 --- a/Jint/Native/Proxy/ProxyConstructor.cs +++ b/Jint/Native/Proxy/ProxyConstructor.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Function; using Jint.Native.Object; using Jint.Runtime; @@ -49,7 +49,7 @@ ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) return Construct(arguments.At(0), arguments.At(1)); } - protected internal override ObjectInstance GetPrototypeOf() + protected internal override ObjectInstance? GetPrototypeOf() { return _realm.Intrinsics.Function.Prototype; } @@ -72,7 +72,7 @@ private JsValue Revocable(JsValue thisObject, JsValue[] arguments) JsValue Revoke(JsValue thisObject, JsValue[] arguments) { p._handler = null; - p._target = null; + p._target = null!; return Undefined; } diff --git a/Jint/Native/Proxy/ProxyInstance.cs b/Jint/Native/Proxy/ProxyInstance.cs index d504f87733..35e59dba7c 100644 --- a/Jint/Native/Proxy/ProxyInstance.cs +++ b/Jint/Native/Proxy/ProxyInstance.cs @@ -1,4 +1,4 @@ -using Jint.Native.Function; +using Jint.Native.Function; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -8,7 +8,7 @@ namespace Jint.Native.Proxy public sealed class ProxyInstance : ObjectInstance, IConstructor, ICallable { internal ObjectInstance _target; - internal ObjectInstance _handler; + internal ObjectInstance? _handler; private static readonly JsString TrapApply = new JsString("apply"); private static readonly JsString TrapGet = new JsString("get"); @@ -128,7 +128,7 @@ public override JsValue Get(JsValue property, JsValue receiver) { ExceptionHelper.ThrowTypeError(_engine.Realm); } - if (targetDesc.IsAccessorDescriptor() && !targetDesc.Configurable && targetDesc.Get.IsUndefined() && !result.IsUndefined()) + if (targetDesc.IsAccessorDescriptor() && !targetDesc.Configurable && targetDesc.Get!.IsUndefined() && !result.IsUndefined()) { ExceptionHelper.ThrowTypeError(_engine.Realm, $"'get' on proxy: property '{property}' is a non-configurable accessor property on the proxy target and does not have a getter function, but the trap did not return 'undefined' (got '{result}')"); } @@ -324,7 +324,7 @@ public override bool Set(JsValue property, JsValue value, JsValue receiver) if (targetDesc.IsAccessorDescriptor() && !targetDesc.Configurable) { - if (targetDesc.Set.IsUndefined()) + if (targetDesc.Set!.IsUndefined()) { ExceptionHelper.ThrowTypeError(_engine.Realm); } @@ -504,7 +504,7 @@ public override bool Extensible /// /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof /// - protected internal override ObjectInstance GetPrototypeOf() + protected internal override ObjectInstance? GetPrototypeOf() { if (!TryCallHandler(TrapGetProtoTypeOf, new JsValue[] { _target }, out var handlerProto )) { @@ -566,7 +566,7 @@ private bool TryCallHandler(JsValue propertyName, JsValue[] arguments, out JsVal AssertNotRevoked(propertyName); result = Undefined; - var handlerFunction = _handler.Get(propertyName); + var handlerFunction = _handler!.Get(propertyName); if (!handlerFunction.IsNullOrUndefined()) { var callable = handlerFunction as ICallable; diff --git a/Jint/Native/Reflect/ReflectInstance.cs b/Jint/Native/Reflect/ReflectInstance.cs index 27585e90ad..8a1558e1f2 100644 --- a/Jint/Native/Reflect/ReflectInstance.cs +++ b/Jint/Native/Reflect/ReflectInstance.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Function; using Jint.Native.Object; using Jint.Native.Symbol; diff --git a/Jint/Native/RegExp/RegExpConstructor.cs b/Jint/Native/RegExp/RegExpConstructor.cs index de32762fa8..f7a0e5821f 100644 --- a/Jint/Native/RegExp/RegExpConstructor.cs +++ b/Jint/Native/RegExp/RegExpConstructor.cs @@ -1,4 +1,4 @@ -using System.Text.RegularExpressions; +using System.Text.RegularExpressions; using Esprima; using Jint.Collections; using Jint.Native.Function; @@ -113,7 +113,7 @@ private ObjectInstance RegExpInitialize(RegExpInstance r, JsValue pattern, JsVal var timeout = _engine.Options.Constraints.RegexTimeout; if (timeout.Ticks > 0) { - r.Value = r.Value != null ? new Regex(r.Value.ToString(), r.Value.Options, timeout) : null; + r.Value = new Regex(r.Value.ToString(), r.Value.Options, timeout); } } catch (Exception ex) @@ -134,7 +134,7 @@ private RegExpInstance RegExpAlloc(JsValue newTarget) var r = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.RegExp.PrototypeObject, - static (Engine engine, Realm _, object _) => new RegExpInstance(engine)); + static (Engine engine, Realm _, object? _) => new RegExpInstance(engine)); return r; } @@ -149,7 +149,7 @@ public RegExpInstance Construct(Regex regExp, string source, string flags) var timeout = _engine.Options.Constraints.RegexTimeout; if (timeout.Ticks > 0) { - r.Value = regExp != null ? new Regex(regExp.ToString(), regExp.Options, timeout) : null; + r.Value = new Regex(regExp.ToString(), regExp.Options, timeout); } else { diff --git a/Jint/Native/RegExp/RegExpExtensions.cs b/Jint/Native/RegExp/RegExpExtensions.cs index 49e7790301..0d29054732 100644 --- a/Jint/Native/RegExp/RegExpExtensions.cs +++ b/Jint/Native/RegExp/RegExpExtensions.cs @@ -1,10 +1,11 @@ +using System.Diagnostics.CodeAnalysis; using Jint.Native.Object; namespace Jint.Native.RegExp { internal static class RegExpExtensions { - internal static bool TryGetDefaultRegExpExec(this ObjectInstance o, out Func exec) + internal static bool TryGetDefaultRegExpExec(this ObjectInstance? o, [NotNullWhen(true)] out Func? exec) { if (o is RegExpPrototype prototype) { diff --git a/Jint/Native/RegExp/RegExpInstance.cs b/Jint/Native/RegExp/RegExpInstance.cs index ba0f6c6ad0..69a0e37ee7 100644 --- a/Jint/Native/RegExp/RegExpInstance.cs +++ b/Jint/Native/RegExp/RegExpInstance.cs @@ -1,4 +1,4 @@ -using System.Text.RegularExpressions; +using System.Text.RegularExpressions; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -10,9 +10,9 @@ public class RegExpInstance : ObjectInstance internal const string regExpForMatchingAllCharacters = "(?:)"; internal static readonly JsString PropertyLastIndex = new JsString("lastIndex"); - private string _flags; + private string _flags = null!; - private PropertyDescriptor _prototypeDescriptor; + private PropertyDescriptor _prototypeDescriptor = null!; public RegExpInstance(Engine engine) : base(engine, ObjectClass.RegExp) @@ -20,7 +20,7 @@ public RegExpInstance(Engine engine) Source = regExpForMatchingAllCharacters; } - public Regex Value { get; set; } + public Regex Value { get; set; } = null!; public string Source { get; set; } public string Flags diff --git a/Jint/Native/RegExp/RegExpPrototype.cs b/Jint/Native/RegExp/RegExpPrototype.cs index 8e3145aad5..d6f0374dd4 100644 --- a/Jint/Native/RegExp/RegExpPrototype.cs +++ b/Jint/Native/RegExp/RegExpPrototype.cs @@ -1,4 +1,5 @@ -using System.Globalization; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Text.RegularExpressions; using Jint.Collections; using Jint.Native.Array; @@ -42,7 +43,7 @@ protected override void Initialize() { const PropertyFlag lengthFlags = PropertyFlag.Configurable; - GetSetPropertyDescriptor CreateGetAccessorDescriptor(string name, Func valueExtractor, JsValue protoValue = null) + GetSetPropertyDescriptor CreateGetAccessorDescriptor(string name, Func valueExtractor, JsValue? protoValue = null) { return new GetSetPropertyDescriptor( get: new ClrFunctionInstance(Engine, name, (thisObj, arguments) => @@ -789,7 +790,7 @@ internal static JsValue RegExpExec(ObjectInstance r, string s) return RegExpBuiltinExec(ri, s); } - internal bool TryGetDefaultExec(ObjectInstance o, out Func exec) + internal bool TryGetDefaultExec(ObjectInstance o, [NotNullWhen((true))] out Func? exec) { if (o.Get(PropertyExec) is ClrFunctionInstance functionInstance && functionInstance._func == _defaultExec) { @@ -893,7 +894,7 @@ private static ArrayInstance CreateReturnValueArray(Engine engine, Match match, array.CreateDataProperty(PropertyIndex, match.Index); array.CreateDataProperty(PropertyInput, inputValue); - ObjectInstance groups = null; + ObjectInstance? groups = null; for (uint i = 0; i < match.Groups.Count; i++) { var capture = i < match.Groups.Count ? match.Groups[(int) i] : null; diff --git a/Jint/Native/RegExp/RegExpStringIteratorPrototype.cs b/Jint/Native/RegExp/RegExpStringIteratorPrototype.cs index dd93bdd841..4ebcb9db0d 100644 --- a/Jint/Native/RegExp/RegExpStringIteratorPrototype.cs +++ b/Jint/Native/RegExp/RegExpStringIteratorPrototype.cs @@ -26,4 +26,4 @@ internal IteratorInstance Construct(ObjectInstance iteratingRegExp, string itera return instance; } } -} \ No newline at end of file +} diff --git a/Jint/Native/RegExp/RegExpStringIteratorPrototypeObject.cs b/Jint/Native/RegExp/RegExpStringIteratorPrototypeObject.cs index 2f61f5598a..65edda7b3a 100644 --- a/Jint/Native/RegExp/RegExpStringIteratorPrototypeObject.cs +++ b/Jint/Native/RegExp/RegExpStringIteratorPrototypeObject.cs @@ -23,4 +23,4 @@ internal IteratorInstance Construct(ObjectInstance iteratingRegExp, string itera return instance; } } -} \ No newline at end of file +} diff --git a/Jint/Native/Set/SetConstructor.cs b/Jint/Native/Set/SetConstructor.cs index d122c81b51..40518a866d 100644 --- a/Jint/Native/Set/SetConstructor.cs +++ b/Jint/Native/Set/SetConstructor.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Function; using Jint.Native.Object; using Jint.Native.Symbol; @@ -61,8 +61,8 @@ ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) var set = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.Set.PrototypeObject, - static (Engine engine, Realm _, object _) => new SetInstance(engine)); - + static (Engine engine, Realm _, object? _) => new SetInstance(engine)); + if (arguments.Length > 0 && !arguments[0].IsNullOrUndefined()) { var adderValue = set.Get("add"); diff --git a/Jint/Native/Set/SetInstance.cs b/Jint/Native/Set/SetInstance.cs index 59adac5ca9..f200897ccb 100644 --- a/Jint/Native/Set/SetInstance.cs +++ b/Jint/Native/Set/SetInstance.cs @@ -1,4 +1,5 @@ -using Jint.Native.Object; +using System.Diagnostics.CodeAnalysis; +using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -23,7 +24,7 @@ public override PropertyDescriptor GetOwnProperty(JsValue property) return base.GetOwnProperty(property); } - protected override bool TryGetProperty(JsValue property, out PropertyDescriptor descriptor) + protected override bool TryGetProperty(JsValue property, [NotNullWhen(true)] out PropertyDescriptor? descriptor) { if (property == CommonProperties.Size) { diff --git a/Jint/Native/Set/SetIteratorPrototype.cs b/Jint/Native/Set/SetIteratorPrototype.cs index be5e8d6821..22c68fb1ac 100644 --- a/Jint/Native/Set/SetIteratorPrototype.cs +++ b/Jint/Native/Set/SetIteratorPrototype.cs @@ -63,4 +63,4 @@ public override bool TryIteratorStep(out ObjectInstance nextItem) } } -} \ No newline at end of file +} diff --git a/Jint/Native/Set/SetPrototype.cs b/Jint/Native/Set/SetPrototype.cs index 0cf691a597..59d6714bf9 100644 --- a/Jint/Native/Set/SetPrototype.cs +++ b/Jint/Native/Set/SetPrototype.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Object; using Jint.Native.Symbol; using Jint.Runtime; @@ -122,4 +122,4 @@ private SetInstance AssertSetInstance(JsValue thisObj) return set; } } -} \ No newline at end of file +} diff --git a/Jint/Native/ShadowRealm/ShadowRealmConstructor.cs b/Jint/Native/ShadowRealm/ShadowRealmConstructor.cs index 09b6144f3a..d5f7a6583e 100644 --- a/Jint/Native/ShadowRealm/ShadowRealmConstructor.cs +++ b/Jint/Native/ShadowRealm/ShadowRealmConstructor.cs @@ -1,5 +1,3 @@ -#nullable enable - using Jint.Native.Function; using Jint.Native.Object; using Jint.Runtime; @@ -52,7 +50,7 @@ private ShadowRealmInstance Construct(JsValue newTarget) { var context = new ExecutionContext( scriptOrModule: null, - lexicalEnvironment: realmRec.GlobalEnv, + lexicalEnvironment: realmRec!.GlobalEnv, variableEnvironment: realmRec.GlobalEnv, privateEnvironment: null, realm: realmRec, diff --git a/Jint/Native/ShadowRealm/ShadowRealmInstance.cs b/Jint/Native/ShadowRealm/ShadowRealmInstance.cs index e2056180ca..e6492bb180 100644 --- a/Jint/Native/ShadowRealm/ShadowRealmInstance.cs +++ b/Jint/Native/ShadowRealm/ShadowRealmInstance.cs @@ -1,6 +1,4 @@ -#nullable enable - -using Esprima; +using Esprima; using Esprima.Ast; using Esprima.Utils; using Jint.Native.Function; @@ -152,6 +150,7 @@ private static JsValue WrappedFunctionCreate(Realm throwerRealm, Realm callerRea { ThrowCrossRealmError(throwerRealm, ex.Message); } + return wrapped; } @@ -180,7 +179,6 @@ private static void CopyNameAndLength(WrappedFunction f, ObjectInstance target, var targetLenAsInt = TypeConverter.ToIntegerOrInfinity(targetLen); L = JsNumber.Create(System.Math.Max(targetLenAsInt - argCount, 0)); } - } } diff --git a/Jint/Native/ShadowRealm/ShadowRealmPrototype.cs b/Jint/Native/ShadowRealm/ShadowRealmPrototype.cs index b67e2e71a8..956f8f301e 100644 --- a/Jint/Native/ShadowRealm/ShadowRealmPrototype.cs +++ b/Jint/Native/ShadowRealm/ShadowRealmPrototype.cs @@ -1,5 +1,3 @@ -#nullable enable - using Jint.Collections; using Jint.Native.Object; using Jint.Native.Symbol; diff --git a/Jint/Native/String/StringConstructor.cs b/Jint/Native/String/StringConstructor.cs index 5f2d6743d9..d200232aee 100644 --- a/Jint/Native/String/StringConstructor.cs +++ b/Jint/Native/String/StringConstructor.cs @@ -46,7 +46,7 @@ protected override void Initialize() /// /// https://tc39.es/ecma262/#sec-string.fromcharcode /// - private static JsValue FromCharCode(JsValue thisObj, JsValue[] arguments) + private static JsValue FromCharCode(JsValue? thisObj, JsValue[] arguments) { var length = arguments.Length; @@ -196,11 +196,9 @@ public StringInstance Construct(JsString value) /// private StringInstance StringCreate(JsString value, ObjectInstance prototype) { - var instance = new StringInstance(Engine) + var instance = new StringInstance(Engine, value) { - _prototype = prototype, - StringData = value, - _length = PropertyDescriptor.AllForbiddenDescriptor.ForNumber(value.Length) + _prototype = prototype }; return instance; diff --git a/Jint/Native/String/StringExecutionContext.cs b/Jint/Native/String/StringExecutionContext.cs index eb91b1f92a..fdbd755e83 100644 --- a/Jint/Native/String/StringExecutionContext.cs +++ b/Jint/Native/String/StringExecutionContext.cs @@ -1,4 +1,4 @@ -using System.Threading; +using System.Threading; namespace Jint.Native.String { @@ -9,8 +9,8 @@ internal sealed class StringExecutionContext { private static readonly ThreadLocal _executionContext = new ThreadLocal(() => new StringExecutionContext()); - private List _splitSegmentList; - private string[] _splitArray1; + private List? _splitSegmentList; + private string[]? _splitArray1; private StringExecutionContext() { diff --git a/Jint/Native/String/StringInstance.cs b/Jint/Native/String/StringInstance.cs index dd5df74a1d..b7ff1cd4ef 100644 --- a/Jint/Native/String/StringInstance.cs +++ b/Jint/Native/String/StringInstance.cs @@ -1,4 +1,4 @@ -using Jint.Native.Object; +using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -6,18 +6,20 @@ namespace Jint.Native.String { public class StringInstance : ObjectInstance, IPrimitiveInstance { - internal PropertyDescriptor _length; + internal PropertyDescriptor? _length; - public StringInstance(Engine engine) + public StringInstance(Engine engine, JsString value) : base(engine, ObjectClass.String) { + StringData = value; + _length = PropertyDescriptor.AllForbiddenDescriptor.ForNumber(value.Length); } Types IPrimitiveInstance.Type => Types.String; JsValue IPrimitiveInstance.PrimitiveValue => StringData; - public JsString StringData { get; internal init; } + public JsString StringData { get; } private static bool IsInt32(double d, out int intValue) { diff --git a/Jint/Native/String/StringIteratorPrototype.cs b/Jint/Native/String/StringIteratorPrototype.cs index 976eef9e53..1c9dbee492 100644 --- a/Jint/Native/String/StringIteratorPrototype.cs +++ b/Jint/Native/String/StringIteratorPrototype.cs @@ -26,4 +26,4 @@ public ObjectInstance Construct(string str) return instance; } } -} \ No newline at end of file +} diff --git a/Jint/Native/String/StringPrototype.cs b/Jint/Native/String/StringPrototype.cs index 3a1288af33..c7647250be 100644 --- a/Jint/Native/String/StringPrototype.cs +++ b/Jint/Native/String/StringPrototype.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using System.Text; using Jint.Collections; using Jint.Native.Object; @@ -24,10 +24,9 @@ internal StringPrototype( Realm realm, StringConstructor constructor, ObjectPrototype objectPrototype) - : base(engine) + : base(engine, JsString.Empty) { _prototype = objectPrototype; - StringData = JsString.Empty; _length = PropertyDescriptor.AllForbiddenDescriptor.NumberZero; _realm = realm; _constructor = constructor; diff --git a/Jint/Native/Symbol/GlobalSymbolRegistry.cs b/Jint/Native/Symbol/GlobalSymbolRegistry.cs index 48f8b2e510..29c3eb9ae5 100644 --- a/Jint/Native/Symbol/GlobalSymbolRegistry.cs +++ b/Jint/Native/Symbol/GlobalSymbolRegistry.cs @@ -1,4 +1,6 @@ -namespace Jint.Native.Symbol +using System.Diagnostics.CodeAnalysis; + +namespace Jint.Native.Symbol { public class GlobalSymbolRegistry { @@ -17,9 +19,9 @@ public class GlobalSymbolRegistry public static readonly JsSymbol Unscopables = new JsSymbol("Symbol.unscopables"); // engine-specific created by scripts - private Dictionary _customSymbolLookup; + private Dictionary? _customSymbolLookup; - internal bool TryGetSymbol(JsValue key, out JsSymbol symbol) + internal bool TryGetSymbol(JsValue key, [NotNullWhen(true)] out JsSymbol? symbol) { symbol = null; return _customSymbolLookup != null diff --git a/Jint/Native/Symbol/SymbolConstructor.cs b/Jint/Native/Symbol/SymbolConstructor.cs index c06bff4969..a875bc4b4d 100644 --- a/Jint/Native/Symbol/SymbolConstructor.cs +++ b/Jint/Native/Symbol/SymbolConstructor.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Function; using Jint.Native.Object; using Jint.Runtime; diff --git a/Jint/Native/Symbol/SymbolInstance.cs b/Jint/Native/Symbol/SymbolInstance.cs index 159bbf58b5..49f2368dc2 100644 --- a/Jint/Native/Symbol/SymbolInstance.cs +++ b/Jint/Native/Symbol/SymbolInstance.cs @@ -1,4 +1,4 @@ -using Jint.Native.Object; +using Jint.Native.Object; using Jint.Runtime; namespace Jint.Native.Symbol diff --git a/Jint/Native/Symbol/SymbolPrototype.cs b/Jint/Native/Symbol/SymbolPrototype.cs index 0bb5468dfa..3fd5a32a4c 100644 --- a/Jint/Native/Symbol/SymbolPrototype.cs +++ b/Jint/Native/Symbol/SymbolPrototype.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; diff --git a/Jint/Native/TypedArray/IntrinsicTypedArrayConstructor.cs b/Jint/Native/TypedArray/IntrinsicTypedArrayConstructor.cs index 92f11892fd..1c3176276c 100644 --- a/Jint/Native/TypedArray/IntrinsicTypedArrayConstructor.cs +++ b/Jint/Native/TypedArray/IntrinsicTypedArrayConstructor.cs @@ -105,7 +105,7 @@ private JsValue From(JsValue thisObj, JsValue[] arguments) JsValue mappedValue; if (mapping) { - mappingArgs[0] = kValue; + mappingArgs![0] = kValue; mappingArgs[1] = Pk; mappedValue = ((ICallable) mapFunction).Call(thisArg, mappingArgs); } @@ -150,7 +150,7 @@ private JsValue Of(JsValue thisObj, JsValue[] items) /// internal TypedArrayInstance TypedArraySpeciesCreate(TypedArrayInstance exemplar, JsValue[] argumentList) { - var defaultConstructor = exemplar._arrayElementType.GetConstructor(_realm.Intrinsics); + var defaultConstructor = exemplar._arrayElementType.GetConstructor(_realm.Intrinsics)!; var constructor = SpeciesConstructor(exemplar, defaultConstructor); var result = TypedArrayCreate(constructor, argumentList); if (result._contentType != exemplar._contentType) diff --git a/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs b/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs index 5e7a98a16f..1033097548 100644 --- a/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs +++ b/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs @@ -19,7 +19,7 @@ internal sealed class IntrinsicTypedArrayPrototype : ObjectInstance { private readonly Realm _realm; private readonly IntrinsicTypedArrayConstructor _constructor; - private ClrFunctionInstance _originalIteratorFunction; + private ClrFunctionInstance? _originalIteratorFunction; internal IntrinsicTypedArrayPrototype( Engine engine, @@ -1151,7 +1151,7 @@ private JsValue Sort(JsValue thisObj, JsValue[] arguments) var len = obj.Length; var compareArg = arguments.At(0); - ICallable compareFn = null; + ICallable? compareFn = null; if (!compareArg.IsUndefined()) { compareFn = GetCallable(compareArg); @@ -1328,16 +1328,16 @@ private static JsValue ToStringTag(JsValue thisObj, JsValue[] arguments) private sealed class TypedArrayComparer : IComparer { - public static TypedArrayComparer WithFunction(ArrayBufferInstance buffer, ICallable compare) + public static TypedArrayComparer WithFunction(ArrayBufferInstance buffer, ICallable? compare) { return new TypedArrayComparer(buffer, compare); } private readonly ArrayBufferInstance _buffer; - private readonly ICallable _compare; + private readonly ICallable? _compare; private readonly JsValue[] _comparableArray = new JsValue[2]; - private TypedArrayComparer(ArrayBufferInstance buffer, ICallable compare) + private TypedArrayComparer(ArrayBufferInstance buffer, ICallable? compare) { _buffer = buffer; _compare = compare; @@ -1360,7 +1360,7 @@ public int Compare(JsValue x, JsValue y) return (int) v; } - if (x.Type == Types.BigInt || y.Type == Types.BigInt) + if (x!.Type == Types.BigInt || y!.Type == Types.BigInt) { var xBigInt = TypeConverter.ToBigInt(x); var yBigInt = TypeConverter.ToBigInt(y); diff --git a/Jint/Native/TypedArray/TypeArrayHelper.cs b/Jint/Native/TypedArray/TypeArrayHelper.cs index 147f5d0a80..e233c5cb1e 100644 --- a/Jint/Native/TypedArray/TypeArrayHelper.cs +++ b/Jint/Native/TypedArray/TypeArrayHelper.cs @@ -18,4 +18,4 @@ internal static TypedArrayInstance ValidateTypedArray(this JsValue o, Realm real return typedArrayInstance; } } -} \ No newline at end of file +} diff --git a/Jint/Native/TypedArray/TypedArrayConstructor.Types.cs b/Jint/Native/TypedArray/TypedArrayConstructor.Types.cs index f3c53eaf66..c3d00616a8 100644 --- a/Jint/Native/TypedArray/TypedArrayConstructor.Types.cs +++ b/Jint/Native/TypedArray/TypedArrayConstructor.Types.cs @@ -199,4 +199,4 @@ public TypedArrayInstance Construct(ulong[] values) return array; } } -} \ No newline at end of file +} diff --git a/Jint/Native/TypedArray/TypedArrayConstructor.cs b/Jint/Native/TypedArray/TypedArrayConstructor.cs index 1e39e5b95b..b841929750 100644 --- a/Jint/Native/TypedArray/TypedArrayConstructor.cs +++ b/Jint/Native/TypedArray/TypedArrayConstructor.cs @@ -70,7 +70,7 @@ internal ObjectInstance Construct(JsValue[] args, JsValue newTarget) TypedArrayElementType.Uint16 => static intrinsics => intrinsics.Uint16Array.PrototypeObject, TypedArrayElementType.Uint32 => static intrinsics => intrinsics.Uint32Array.PrototypeObject, TypedArrayElementType.BigUint64 => static intrinsics => intrinsics.BigUint64Array.PrototypeObject, - _ => null + _ => null! }; var numberOfArgs = args.Length; @@ -117,7 +117,7 @@ internal ObjectInstance Construct(JsValue[] args, JsValue newTarget) /// /// https://tc39.es/ecma262/#sec-iterabletolist /// - internal static List IterableToList(Realm realm, JsValue items, ICallable method = null) + internal static List IterableToList(Realm realm, JsValue items, ICallable? method = null) { var iteratorRecord = items.GetIterator(realm); var values = new List(); diff --git a/Jint/Native/TypedArray/TypedArrayContentType.cs b/Jint/Native/TypedArray/TypedArrayContentType.cs index fdfe2b65be..a935b93b3b 100644 --- a/Jint/Native/TypedArray/TypedArrayContentType.cs +++ b/Jint/Native/TypedArray/TypedArrayContentType.cs @@ -5,4 +5,4 @@ internal enum TypedArrayContentType : byte Number, BigInt } -} \ No newline at end of file +} diff --git a/Jint/Native/TypedArray/TypedArrayElementType.cs b/Jint/Native/TypedArray/TypedArrayElementType.cs index 54e795bf83..401dfbbaac 100644 --- a/Jint/Native/TypedArray/TypedArrayElementType.cs +++ b/Jint/Native/TypedArray/TypedArrayElementType.cs @@ -55,11 +55,11 @@ internal static string GetTypedArrayName(this TypedArrayElementType type) TypedArrayElementType.BigUint64 => "BigUint64Array", TypedArrayElementType.Float32 => "Float32Array", TypedArrayElementType.Float64 => "Float64Array", - _ => null + _ => "" }; } - internal static IConstructor GetConstructor(this TypedArrayElementType type, Intrinsics intrinsics) + internal static IConstructor? GetConstructor(this TypedArrayElementType type, Intrinsics intrinsics) { return type switch { @@ -93,4 +93,4 @@ internal static bool IsBigIntElementType(this TypedArrayElementType type) return type is TypedArrayElementType.BigUint64 or TypedArrayElementType.BigInt64; } } -} \ No newline at end of file +} diff --git a/Jint/Native/TypedArray/TypedArrayPrototype.cs b/Jint/Native/TypedArray/TypedArrayPrototype.cs index 6c4b1af7a3..1128b456dc 100644 --- a/Jint/Native/TypedArray/TypedArrayPrototype.cs +++ b/Jint/Native/TypedArray/TypedArrayPrototype.cs @@ -33,4 +33,4 @@ protected override void Initialize() SetProperties(properties); } } -} \ No newline at end of file +} diff --git a/Jint/Native/Undefined.cs b/Jint/Native/Undefined.cs index b0a7273d3c..97e66ba043 100644 --- a/Jint/Native/Undefined.cs +++ b/Jint/Native/Undefined.cs @@ -1,8 +1,8 @@ -namespace Jint.Native +namespace Jint.Native { public static class Undefined { public static readonly JsValue Instance = JsValue.Undefined; public const string Text = "undefined"; } -} \ No newline at end of file +} diff --git a/Jint/Native/WeakMap/WeakMapConstructor.cs b/Jint/Native/WeakMap/WeakMapConstructor.cs index 7e13b1e1fc..eeb9d4401c 100644 --- a/Jint/Native/WeakMap/WeakMapConstructor.cs +++ b/Jint/Native/WeakMap/WeakMapConstructor.cs @@ -1,4 +1,4 @@ -using Jint.Native.Function; +using Jint.Native.Function; using Jint.Native.Iterator; using Jint.Native.Object; using Jint.Runtime; @@ -41,7 +41,7 @@ ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) var map = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.WeakMap.PrototypeObject, - static (Engine engine, Realm _, object _) => new WeakMapInstance(engine)); + static (Engine engine, Realm _, object? _) => new WeakMapInstance(engine)); if (arguments.Length > 0 && !arguments[0].IsNullOrUndefined()) { var adder = map.Get("set"); diff --git a/Jint/Native/WeakMap/WeakMapInstance.cs b/Jint/Native/WeakMap/WeakMapInstance.cs index 23c87c3306..0c89e08771 100644 --- a/Jint/Native/WeakMap/WeakMapInstance.cs +++ b/Jint/Native/WeakMap/WeakMapInstance.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using Jint.Native.Object; using Jint.Runtime; diff --git a/Jint/Native/WeakMap/WeakMapPrototype.cs b/Jint/Native/WeakMap/WeakMapPrototype.cs index c459cb7df5..5371da1ec5 100644 --- a/Jint/Native/WeakMap/WeakMapPrototype.cs +++ b/Jint/Native/WeakMap/WeakMapPrototype.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Object; using Jint.Native.Symbol; using Jint.Runtime; @@ -81,4 +81,4 @@ private WeakMapInstance AssertWeakMapInstance(JsValue thisObj) return map; } } -} \ No newline at end of file +} diff --git a/Jint/Native/WeakSet/WeakSetConstructor.cs b/Jint/Native/WeakSet/WeakSetConstructor.cs index ff66a5773a..382aa182de 100644 --- a/Jint/Native/WeakSet/WeakSetConstructor.cs +++ b/Jint/Native/WeakSet/WeakSetConstructor.cs @@ -1,4 +1,4 @@ -using Jint.Native.Function; +using Jint.Native.Function; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -40,8 +40,8 @@ ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) var set = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.WeakSet.PrototypeObject, - static (Engine engine, Realm _, object _) => new WeakSetInstance(engine)); - + static (Engine engine, Realm _, object? _) => new WeakSetInstance(engine)); + if (arguments.Length > 0 && !arguments[0].IsNullOrUndefined()) { var adder = set.Get("add") as ICallable; diff --git a/Jint/Native/WeakSet/WeakSetInstance.cs b/Jint/Native/WeakSet/WeakSetInstance.cs index e93eaa4b77..a94860f35d 100644 --- a/Jint/Native/WeakSet/WeakSetInstance.cs +++ b/Jint/Native/WeakSet/WeakSetInstance.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using Jint.Native.Object; using Jint.Runtime; diff --git a/Jint/Native/WeakSet/WeakSetPrototype.cs b/Jint/Native/WeakSet/WeakSetPrototype.cs index cfadcc4b6c..f00c684a5e 100644 --- a/Jint/Native/WeakSet/WeakSetPrototype.cs +++ b/Jint/Native/WeakSet/WeakSetPrototype.cs @@ -1,4 +1,4 @@ -using Jint.Collections; +using Jint.Collections; using Jint.Native.Object; using Jint.Native.Symbol; using Jint.Runtime; @@ -74,4 +74,4 @@ private WeakSetInstance AssertWeakSetInstance(JsValue thisObj) return set; } } -} \ No newline at end of file +} diff --git a/Jint/Options.Extensions.cs b/Jint/Options.Extensions.cs index 17ec032401..b848f719c7 100644 --- a/Jint/Options.Extensions.cs +++ b/Jint/Options.Extensions.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Globalization; using System.Reflection; using Jint.Native; diff --git a/Jint/Options.cs b/Jint/Options.cs index 4380f5676d..348b3505f0 100644 --- a/Jint/Options.cs +++ b/Jint/Options.cs @@ -1,6 +1,4 @@ -#nullable enable - -using System.Dynamic; +using System.Dynamic; using System.Globalization; using System.Reflection; using Jint.Native; @@ -307,7 +305,7 @@ public class InteropOptions /// Strategy to create a CLR object to hold converted . /// public Func> CreateClrObject = _ => new ExpandoObject(); - + /// /// When not null, is used to serialize any CLR object in an /// passing through 'JSON.stringify'. diff --git a/Jint/Pooling/ArgumentsInstancePool.cs b/Jint/Pooling/ArgumentsInstancePool.cs index c22884b612..2f7e98fc35 100644 --- a/Jint/Pooling/ArgumentsInstancePool.cs +++ b/Jint/Pooling/ArgumentsInstancePool.cs @@ -1,4 +1,4 @@ -using Jint.Native; +using Jint.Native; using Jint.Native.Argument; using Jint.Native.Function; using Jint.Runtime.Environments; @@ -32,14 +32,14 @@ private ArgumentsInstance Factory() public ArgumentsInstance Rent(JsValue[] argumentsList) => Rent(null, null, argumentsList, null, false); public ArgumentsInstance Rent( - FunctionInstance func, - Key[] formals, + FunctionInstance? func, + Key[]? formals, JsValue[] argumentsList, - DeclarativeEnvironmentRecord env, + DeclarativeEnvironmentRecord? env, bool hasRestParameter) { var obj = _pool.Allocate(); - obj.Prepare(func, formals, argumentsList, env, hasRestParameter); + obj.Prepare(func!, formals!, argumentsList, env!, hasRestParameter); return obj; } @@ -52,4 +52,4 @@ public void Return(ArgumentsInstance instance) _pool.Free(instance);; } } -} \ No newline at end of file +} diff --git a/Jint/Pooling/ConcurrentObjectPool.cs b/Jint/Pooling/ConcurrentObjectPool.cs index 5319359193..596579c364 100644 --- a/Jint/Pooling/ConcurrentObjectPool.cs +++ b/Jint/Pooling/ConcurrentObjectPool.cs @@ -1,3 +1,5 @@ +#nullable disable + // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // define TRACE_LEAKS to get additional diagnostics that can lead to the leak sources. note: it will diff --git a/Jint/Pooling/JsValueArrayPool.cs b/Jint/Pooling/JsValueArrayPool.cs index c49ca2f899..e8c9d7b651 100644 --- a/Jint/Pooling/JsValueArrayPool.cs +++ b/Jint/Pooling/JsValueArrayPool.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using Jint.Native; namespace Jint.Pooling @@ -75,4 +75,4 @@ public void ReturnArray(JsValue[] array) } } } -} \ No newline at end of file +} diff --git a/Jint/Pooling/ObjectPool.cs b/Jint/Pooling/ObjectPool.cs index 25cd77d8ef..7eb41caeea 100644 --- a/Jint/Pooling/ObjectPool.cs +++ b/Jint/Pooling/ObjectPool.cs @@ -1,4 +1,6 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +#nullable disable + +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // define TRACE_LEAKS to get additional diagnostics that can lead to the leak sources. note: it will // make everything about 2-3x slower diff --git a/Jint/Pooling/ReferencePool.cs b/Jint/Pooling/ReferencePool.cs index fd65af7c5c..7d6420bd93 100644 --- a/Jint/Pooling/ReferencePool.cs +++ b/Jint/Pooling/ReferencePool.cs @@ -1,4 +1,4 @@ -using Jint.Native; +using Jint.Native; using Jint.Runtime.References; namespace Jint.Pooling @@ -21,12 +21,12 @@ private static Reference Factory() return new Reference(JsValue.Undefined, JsString.Empty, false, null); } - public Reference Rent(JsValue baseValue, JsValue name, bool strict, JsValue thisValue) + public Reference Rent(JsValue baseValue, JsValue name, bool strict, JsValue? thisValue) { return _pool.Allocate().Reassign(baseValue, name, strict, thisValue); } - public void Return(Reference reference) + public void Return(Reference? reference) { if (reference == null) { @@ -35,4 +35,4 @@ public void Return(Reference reference) _pool.Free(reference);; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Arguments.cs b/Jint/Runtime/Arguments.cs index 778df96893..8536d35510 100644 --- a/Jint/Runtime/Arguments.cs +++ b/Jint/Runtime/Arguments.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using Jint.Native; namespace Jint.Runtime diff --git a/Jint/Runtime/CallStack/CallStackElement.cs b/Jint/Runtime/CallStack/CallStackElement.cs index 4ffc95c46a..09198962f8 100644 --- a/Jint/Runtime/CallStack/CallStackElement.cs +++ b/Jint/Runtime/CallStack/CallStackElement.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima; using Esprima.Ast; using Jint.Native.Function; diff --git a/Jint/Runtime/CallStack/CallStackElementComparer.cs b/Jint/Runtime/CallStack/CallStackElementComparer.cs index 207263b5d4..4235d40db2 100644 --- a/Jint/Runtime/CallStack/CallStackElementComparer.cs +++ b/Jint/Runtime/CallStack/CallStackElementComparer.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Jint.Runtime.CallStack { internal sealed class CallStackElementComparer: IEqualityComparer diff --git a/Jint/Runtime/CallStack/JintCallStack.cs b/Jint/Runtime/CallStack/JintCallStack.cs index 7aac487aeb..69cfba2bf4 100644 --- a/Jint/Runtime/CallStack/JintCallStack.cs +++ b/Jint/Runtime/CallStack/JintCallStack.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Diagnostics.CodeAnalysis; using System.Text; using Esprima; diff --git a/Jint/Runtime/CommonProperties.cs b/Jint/Runtime/CommonProperties.cs index fc5791dd1a..6605e206cb 100644 --- a/Jint/Runtime/CommonProperties.cs +++ b/Jint/Runtime/CommonProperties.cs @@ -26,4 +26,4 @@ internal static class CommonProperties internal static readonly JsString Stack = new JsString("stack"); internal static readonly JsString Message = new JsString("message"); } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Completion.cs b/Jint/Runtime/Completion.cs index ad0f57cca1..5f9bcbea65 100644 --- a/Jint/Runtime/Completion.cs +++ b/Jint/Runtime/Completion.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Runtime.CompilerServices; using Esprima; using Jint.Native; diff --git a/Jint/Runtime/Debugger/BreakLocation.cs b/Jint/Runtime/Debugger/BreakLocation.cs index 82092e7edc..3aa542444e 100644 --- a/Jint/Runtime/Debugger/BreakLocation.cs +++ b/Jint/Runtime/Debugger/BreakLocation.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Jint.Runtime.Debugger; /// diff --git a/Jint/Runtime/Debugger/BreakPoint.cs b/Jint/Runtime/Debugger/BreakPoint.cs index 9caad7b539..37a7e00166 100644 --- a/Jint/Runtime/Debugger/BreakPoint.cs +++ b/Jint/Runtime/Debugger/BreakPoint.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Jint.Runtime.Debugger; // BreakPoint is not sealed. It's useful to be able to add additional properties on a derived BreakPoint class (e.g. a breakpoint ID diff --git a/Jint/Runtime/Debugger/BreakPointCollection.cs b/Jint/Runtime/Debugger/BreakPointCollection.cs index 09386c19bf..7407b63e5f 100644 --- a/Jint/Runtime/Debugger/BreakPointCollection.cs +++ b/Jint/Runtime/Debugger/BreakPointCollection.cs @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; namespace Jint.Runtime.Debugger { @@ -61,7 +61,7 @@ public void Clear() _breakPoints.Clear(); } - internal BreakPoint FindMatch(DebugHandler debugger, BreakLocation location) + internal BreakPoint? FindMatch(DebugHandler debugger, BreakLocation location) { if (!Active) { @@ -77,7 +77,7 @@ internal BreakPoint FindMatch(DebugHandler debugger, BreakLocation location) { try { - var completionValue = debugger.Evaluate(breakPoint.Condition); + var completionValue = debugger.Evaluate(breakPoint.Condition!); // Truthiness check: if (!TypeConverter.ToBoolean(completionValue)) diff --git a/Jint/Runtime/Debugger/CallFrame.cs b/Jint/Runtime/Debugger/CallFrame.cs index 9190e3af50..320e70736c 100644 --- a/Jint/Runtime/Debugger/CallFrame.cs +++ b/Jint/Runtime/Debugger/CallFrame.cs @@ -1,4 +1,4 @@ -using Esprima; +using Esprima; using Esprima.Ast; using Jint.Native; using Jint.Runtime.CallStack; @@ -12,7 +12,7 @@ public sealed class CallFrame private readonly CallStackElement? _element; private readonly Lazy _scopeChain; - internal CallFrame(CallStackElement? element, ExecutionContext context, Location location, JsValue returnValue) + internal CallFrame(CallStackElement? element, ExecutionContext context, Location location, JsValue? returnValue) { _element = element; _context = context; @@ -62,6 +62,6 @@ public JsValue This /// The return value of this call frame. Will be null for call frames that aren't at the top of the stack, /// as well as if execution is not at a return point. /// - public JsValue ReturnValue { get; } + public JsValue? ReturnValue { get; } } } diff --git a/Jint/Runtime/Debugger/DebugCallStack.cs b/Jint/Runtime/Debugger/DebugCallStack.cs index 719a539449..5bad0b9e0f 100644 --- a/Jint/Runtime/Debugger/DebugCallStack.cs +++ b/Jint/Runtime/Debugger/DebugCallStack.cs @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; using Esprima; using Jint.Native; using Jint.Runtime.CallStack; @@ -9,7 +9,7 @@ public sealed class DebugCallStack : IReadOnlyList { private readonly List _stack; - internal DebugCallStack(Engine engine, Location location, JintCallStack callStack, JsValue returnValue) + internal DebugCallStack(Engine engine, Location location, JintCallStack callStack, JsValue? returnValue) { _stack = new List(callStack.Count + 1); var executionContext = engine.ExecutionContext; diff --git a/Jint/Runtime/Debugger/DebugEvaluationException.cs b/Jint/Runtime/Debugger/DebugEvaluationException.cs index 3e74936171..4241973efd 100644 --- a/Jint/Runtime/Debugger/DebugEvaluationException.cs +++ b/Jint/Runtime/Debugger/DebugEvaluationException.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Jint.Runtime.Debugger; /// diff --git a/Jint/Runtime/Debugger/DebugHandler.cs b/Jint/Runtime/Debugger/DebugHandler.cs index f995d73f4c..4bc8154018 100644 --- a/Jint/Runtime/Debugger/DebugHandler.cs +++ b/Jint/Runtime/Debugger/DebugHandler.cs @@ -28,7 +28,7 @@ public class DebugHandler /// still be paused by a debugger statement or breakpoint, but these will trigger the /// event. /// - public event DebugEventHandler Step; + public event DebugEventHandler? Step; /// /// The Break event is triggered when a breakpoint or debugger statement is hit. @@ -37,7 +37,7 @@ public class DebugHandler /// This is event is not triggered if the current script location was reached by stepping. In that case, only /// the event is triggered. /// - public event DebugEventHandler Break; + public event DebugEventHandler? Break; internal DebugHandler(Engine engine, StepMode initialStepMode) { @@ -108,7 +108,7 @@ public JsValue Evaluate(Script script) } /// - public JsValue Evaluate(string source, ParserOptions options = null) + public JsValue Evaluate(string source, ParserOptions? options = null) { options ??= new ParserOptions("evaluation"); var parser = new JavaScriptParser(source, options); @@ -133,7 +133,7 @@ internal void OnStep(Node node) _paused = true; CheckBreakPointAndPause( - new BreakLocation(node.Location.Source, node.Location.Start), + new BreakLocation(node.Location.Source!, node.Location.Start), node: node, location: null, returnValue: null); @@ -153,7 +153,7 @@ internal void OnReturnPoint(Node functionBody, JsValue returnValue) var location = new Location(functionBodyEnd, functionBodyEnd, bodyLocation.Source); CheckBreakPointAndPause( - new BreakLocation(bodyLocation.Source, bodyLocation.End), + new BreakLocation(bodyLocation.Source!, bodyLocation.End), node: null, location: location, returnValue: returnValue); @@ -180,11 +180,14 @@ internal void OnDebuggerStatement(Statement statement) _paused = false; } - private void CheckBreakPointAndPause(BreakLocation breakLocation, Node node = null, Location? location = null, - JsValue returnValue = null) + private void CheckBreakPointAndPause( + BreakLocation breakLocation, + Node? node, + Location? location = null, + JsValue? returnValue = null) { CurrentLocation = location ?? node?.Location; - BreakPoint breakpoint = BreakPoints.FindMatch(this, breakLocation); + var breakpoint = BreakPoints.FindMatch(this, breakLocation); bool isStepping = _engine.CallStack.Count <= _steppingDepth; @@ -193,19 +196,23 @@ private void CheckBreakPointAndPause(BreakLocation breakLocation, Node node = nu // Even if we matched a breakpoint, if we're stepping, the reason we're pausing is the step. // Still, we need to include the breakpoint at this location, in case the debugger UI needs to update // e.g. a hit count. - Pause(isStepping ? PauseType.Step : PauseType.Break, node, location, returnValue, breakpoint); + Pause(isStepping ? PauseType.Step : PauseType.Break, node!, location, returnValue, breakpoint); } _paused = false; } - private void Pause(PauseType type, Node node = null, Location? location = null, JsValue returnValue = null, - BreakPoint breakPoint = null) + private void Pause( + PauseType type, + Node node, + Location? location = null, + JsValue? returnValue = null, + BreakPoint? breakPoint = null) { var info = new DebugInformation( engine: _engine, currentNode: node, - currentLocation: location ?? node.Location, + currentLocation: location ?? node!.Location, returnValue: returnValue, currentMemoryUsage: _engine.CurrentMemoryUsage, pauseType: type, diff --git a/Jint/Runtime/Debugger/DebugInformation.cs b/Jint/Runtime/Debugger/DebugInformation.cs index 924867e863..209b031d95 100644 --- a/Jint/Runtime/Debugger/DebugInformation.cs +++ b/Jint/Runtime/Debugger/DebugInformation.cs @@ -8,12 +8,18 @@ public sealed class DebugInformation : EventArgs { private readonly Engine _engine; private readonly Location _currentLocation; - private readonly JsValue _returnValue; + private readonly JsValue? _returnValue; - private DebugCallStack _callStack; + private DebugCallStack? _callStack; - internal DebugInformation(Engine engine, Node currentNode, Location currentLocation, JsValue returnValue, - long currentMemoryUsage, PauseType pauseType, BreakPoint breakPoint) + internal DebugInformation( + Engine engine, + Node currentNode, + Location currentLocation, + JsValue? returnValue, + long currentMemoryUsage, + PauseType pauseType, + BreakPoint? breakPoint) { _engine = engine; CurrentNode = currentNode; @@ -32,7 +38,7 @@ internal DebugInformation(Engine engine, Node currentNode, Location currentLocat /// /// Breakpoint at the current location. This will be set even if the pause wasn't caused by the breakpoint. /// - public BreakPoint BreakPoint { get; } + public BreakPoint? BreakPoint { get; } /// /// The current call stack. @@ -72,6 +78,6 @@ internal DebugInformation(Engine engine, Node currentNode, Location currentLocat /// The return value of the currently executing call frame. /// This is null if execution is not at a return point. /// - public JsValue ReturnValue => CurrentCallFrame.ReturnValue; + public JsValue? ReturnValue => CurrentCallFrame.ReturnValue; } } diff --git a/Jint/Runtime/Debugger/DebugScope.cs b/Jint/Runtime/Debugger/DebugScope.cs index 6df85b4ae3..6f9b28b8a4 100644 --- a/Jint/Runtime/Debugger/DebugScope.cs +++ b/Jint/Runtime/Debugger/DebugScope.cs @@ -1,4 +1,4 @@ -using Jint.Native; +using Jint.Native; using Jint.Native.Object; using Jint.Runtime.Environments; @@ -48,14 +48,14 @@ internal DebugScope(DebugScopeType type, EnvironmentRecord record, List /// This is mainly useful as an optimization for devtools, allowing the BindingObject to be serialized directly rather than /// building a new transient object in response to e.g. Runtime.getProperties. /// - public ObjectInstance BindingObject { get; } + public ObjectInstance? BindingObject { get; } /// /// Retrieves the value of a specific binding. Note that some bindings (e.g. uninitialized let/const) may return null. /// /// Binding name /// Value of the binding - public JsValue GetBindingValue(string name) + public JsValue? GetBindingValue(string name) { _record.TryGetBindingValue(name, strict: true, out var result); return result; diff --git a/Jint/Runtime/Debugger/DebugScopeType.cs b/Jint/Runtime/Debugger/DebugScopeType.cs index f48ca4be73..ac4bcda3a4 100644 --- a/Jint/Runtime/Debugger/DebugScopeType.cs +++ b/Jint/Runtime/Debugger/DebugScopeType.cs @@ -1,4 +1,4 @@ -namespace Jint.Runtime.Debugger +namespace Jint.Runtime.Debugger { /// /// Variable scope type. diff --git a/Jint/Runtime/Debugger/DebugScopes.cs b/Jint/Runtime/Debugger/DebugScopes.cs index 6dc24c7d18..d1e90cbca2 100644 --- a/Jint/Runtime/Debugger/DebugScopes.cs +++ b/Jint/Runtime/Debugger/DebugScopes.cs @@ -1,4 +1,4 @@ -using Jint.Runtime.Environments; +using Jint.Runtime.Environments; using System.Collections; namespace Jint.Runtime.Debugger @@ -20,7 +20,7 @@ internal DebugScopes(EnvironmentRecord environment) /// Note that this only includes the object environment record of the Global scope - i.e. it doesn't /// include block scope bindings (let/const). /// - public DebugScope Global { get; private set; } + public DebugScope? Global { get; private set; } /// /// Shortcut to Local scope. @@ -28,17 +28,17 @@ internal DebugScopes(EnvironmentRecord environment) /// /// Note that this is only present inside functions, and doesn't include block scope bindings (let/const) /// - public DebugScope Local { get; private set; } + public DebugScope? Local { get; private set; } public DebugScope this[int index] => _scopes[index]; public int Count => _scopes.Count; - private void Populate(EnvironmentRecord environment) + private void Populate(EnvironmentRecord? environment) { bool inLocalScope = true; while (environment != null) { - EnvironmentRecord record = environment; + var record = environment; switch (record) { case GlobalEnvironmentRecord global: diff --git a/Jint/Runtime/Debugger/DebuggerStatementHandling.cs b/Jint/Runtime/Debugger/DebuggerStatementHandling.cs index 0126bcdc64..ff756eb121 100644 --- a/Jint/Runtime/Debugger/DebuggerStatementHandling.cs +++ b/Jint/Runtime/Debugger/DebuggerStatementHandling.cs @@ -1,4 +1,4 @@ -namespace Jint.Runtime.Debugger +namespace Jint.Runtime.Debugger { /// /// Choice of handling for script debugger statements. diff --git a/Jint/Runtime/Debugger/OptionalSourceBreakLocationEqualityComparer.cs b/Jint/Runtime/Debugger/OptionalSourceBreakLocationEqualityComparer.cs index 360589d7a5..c7e7e9ade3 100644 --- a/Jint/Runtime/Debugger/OptionalSourceBreakLocationEqualityComparer.cs +++ b/Jint/Runtime/Debugger/OptionalSourceBreakLocationEqualityComparer.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Jint.Runtime.Debugger; /// @@ -13,7 +11,7 @@ internal sealed class OptionalSourceBreakLocationEqualityComparer : IEqualityCom { public bool Equals(BreakLocation? x, BreakLocation? y) { - if (Object.ReferenceEquals(x, y)) + if (ReferenceEquals(x, y)) { return true; } diff --git a/Jint/Runtime/Debugger/StepMode.cs b/Jint/Runtime/Debugger/StepMode.cs index 64984f828a..36f3978713 100644 --- a/Jint/Runtime/Debugger/StepMode.cs +++ b/Jint/Runtime/Debugger/StepMode.cs @@ -1,4 +1,4 @@ -namespace Jint.Runtime.Debugger +namespace Jint.Runtime.Debugger { public enum StepMode { diff --git a/Jint/Runtime/DefaultReferenceResolver.cs b/Jint/Runtime/DefaultReferenceResolver.cs index f794040479..d4b1aa7254 100644 --- a/Jint/Runtime/DefaultReferenceResolver.cs +++ b/Jint/Runtime/DefaultReferenceResolver.cs @@ -34,4 +34,4 @@ public bool CheckCoercible(JsValue value) return false; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Descriptors/GetSetPropertyDescriptor.cs b/Jint/Runtime/Descriptors/GetSetPropertyDescriptor.cs index 3d553fd71c..8a3b51ea07 100644 --- a/Jint/Runtime/Descriptors/GetSetPropertyDescriptor.cs +++ b/Jint/Runtime/Descriptors/GetSetPropertyDescriptor.cs @@ -1,20 +1,20 @@ -using Jint.Native; +using Jint.Native; namespace Jint.Runtime.Descriptors { public sealed class GetSetPropertyDescriptor : PropertyDescriptor { - private JsValue _get; - private JsValue _set; + private JsValue? _get; + private JsValue? _set; - public GetSetPropertyDescriptor(JsValue get, JsValue set, bool? enumerable = null, bool? configurable = null) + public GetSetPropertyDescriptor(JsValue? get, JsValue? set, bool? enumerable = null, bool? configurable = null) : base(null, writable: null, enumerable: enumerable, configurable: configurable) { _get = get; _set = set; } - internal GetSetPropertyDescriptor(JsValue get, JsValue set, PropertyFlag flags) + internal GetSetPropertyDescriptor(JsValue? get, JsValue? set, PropertyFlag flags) : base(null, flags) { _get = get; @@ -27,8 +27,8 @@ public GetSetPropertyDescriptor(PropertyDescriptor descriptor) : base(descriptor _set = descriptor.Set; } - public override JsValue Get => _get; - public override JsValue Set => _set; + public override JsValue? Get => _get; + public override JsValue? Set => _set; internal void SetGet(JsValue getter) { @@ -43,7 +43,7 @@ internal void SetSet(JsValue setter) internal sealed class ThrowerPropertyDescriptor : PropertyDescriptor { private readonly Engine _engine; - private JsValue _thrower; + private JsValue? _thrower; public ThrowerPropertyDescriptor(Engine engine, PropertyFlag flags) : base(flags) { @@ -53,10 +53,10 @@ public ThrowerPropertyDescriptor(Engine engine, PropertyFlag flags) : base(flags public override JsValue Get => _thrower ??= _engine.Realm.Intrinsics.ThrowTypeError; public override JsValue Set => _thrower ??= _engine.Realm.Intrinsics.ThrowTypeError; - protected internal override JsValue CustomValue + protected internal override JsValue? CustomValue { set => ExceptionHelper.ThrowInvalidOperationException("making changes to throw type error property's descriptor is not allowed"); } } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Descriptors/PropertyDescriptor.cs b/Jint/Runtime/Descriptors/PropertyDescriptor.cs index 9aa599d386..4ff3e3cc68 100644 --- a/Jint/Runtime/Descriptors/PropertyDescriptor.cs +++ b/Jint/Runtime/Descriptors/PropertyDescriptor.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; using System.Runtime.CompilerServices; using Jint.Collections; using Jint.Native; @@ -12,7 +12,7 @@ public class PropertyDescriptor public static readonly PropertyDescriptor Undefined = new UndefinedPropertyDescriptor(); internal PropertyFlag _flags; - internal JsValue _value; + internal JsValue? _value; public PropertyDescriptor() : this(PropertyFlag.None) { @@ -23,7 +23,7 @@ protected PropertyDescriptor(PropertyFlag flags) _flags = flags; } - protected internal PropertyDescriptor(JsValue value, PropertyFlag flags) : this(flags) + protected internal PropertyDescriptor(JsValue? value, PropertyFlag flags) : this(flags) { if ((_flags & PropertyFlag.CustomJsValue) != 0) { @@ -32,7 +32,7 @@ protected internal PropertyDescriptor(JsValue value, PropertyFlag flags) : this( _value = value; } - public PropertyDescriptor(JsValue value, bool? writable, bool? enumerable, bool? configurable) + public PropertyDescriptor(JsValue? value, bool? writable, bool? enumerable, bool? configurable) { if ((_flags & PropertyFlag.CustomJsValue) != 0) { @@ -73,8 +73,8 @@ public PropertyDescriptor(PropertyDescriptor descriptor) WritableSet = descriptor.WritableSet; } - public virtual JsValue Get => null; - public virtual JsValue Set => null; + public virtual JsValue? Get => null; + public virtual JsValue? Set => null; public bool Enumerable { @@ -194,10 +194,10 @@ public JsValue Value { if ((_flags & PropertyFlag.CustomJsValue) != 0) { - return CustomValue; + return CustomValue!; } - return _value; + return _value!; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set @@ -210,7 +210,7 @@ public JsValue Value } } - protected internal virtual JsValue CustomValue + protected internal virtual JsValue? CustomValue { get => null; set => ExceptionHelper.ThrowNotImplementedException(); @@ -405,7 +405,7 @@ internal bool TryGetValue(ObjectInstance thisArg, out JsValue value) if (!ReferenceEquals(getter, null) && !getter.IsUndefined()) { // if getter is not undefined it must be ICallable - var callable = getter.TryCast(); + var callable = (ICallable) getter; value = callable.Call(thisArg, Arguments.Empty); } @@ -418,7 +418,7 @@ public UndefinedPropertyDescriptor() : base(PropertyFlag.None | PropertyFlag.Cus { } - protected internal override JsValue CustomValue + protected internal override JsValue? CustomValue { set => ExceptionHelper.ThrowInvalidOperationException("making changes to undefined property's descriptor is not allowed"); } @@ -458,4 +458,4 @@ public static PropertyDescriptor ForNumber(int number) } } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Descriptors/PropertyFlag.cs b/Jint/Runtime/Descriptors/PropertyFlag.cs index ae1bc9e4be..ac1a6231e3 100644 --- a/Jint/Runtime/Descriptors/PropertyFlag.cs +++ b/Jint/Runtime/Descriptors/PropertyFlag.cs @@ -1,4 +1,4 @@ -namespace Jint.Runtime.Descriptors +namespace Jint.Runtime.Descriptors { [Flags] public enum PropertyFlag diff --git a/Jint/Runtime/Descriptors/Specialized/ClrAccessDescriptor.cs b/Jint/Runtime/Descriptors/Specialized/ClrAccessDescriptor.cs index ba6a120ff1..3dee3f8192 100644 --- a/Jint/Runtime/Descriptors/Specialized/ClrAccessDescriptor.cs +++ b/Jint/Runtime/Descriptors/Specialized/ClrAccessDescriptor.cs @@ -1,4 +1,4 @@ -using Jint.Native; +using Jint.Native; using Jint.Runtime.Environments; using Jint.Runtime.Interop; @@ -10,8 +10,8 @@ internal sealed class ClrAccessDescriptor : PropertyDescriptor private readonly Engine _engine; private readonly EnvironmentRecord.BindingName _name; - private GetterFunctionInstance _get; - private SetterFunctionInstance _set; + private GetterFunctionInstance? _get; + private SetterFunctionInstance? _set; public ClrAccessDescriptor( DeclarativeEnvironmentRecord env, diff --git a/Jint/Runtime/Descriptors/Specialized/LazyPropertyDescriptor.cs b/Jint/Runtime/Descriptors/Specialized/LazyPropertyDescriptor.cs index 06d889115e..7c2eaec1df 100644 --- a/Jint/Runtime/Descriptors/Specialized/LazyPropertyDescriptor.cs +++ b/Jint/Runtime/Descriptors/Specialized/LazyPropertyDescriptor.cs @@ -4,17 +4,17 @@ namespace Jint.Runtime.Descriptors.Specialized { internal sealed class LazyPropertyDescriptor : PropertyDescriptor { - private readonly object _state; - private readonly Func _resolver; + private readonly object? _state; + private readonly Func _resolver; - internal LazyPropertyDescriptor(object state, Func resolver, PropertyFlag flags) + internal LazyPropertyDescriptor(object? state, Func resolver, PropertyFlag flags) : base(null, flags | PropertyFlag.CustomJsValue) { _state = state; _resolver = resolver; } - protected internal override JsValue CustomValue + protected internal override JsValue? CustomValue { get => _value ??= _resolver(_state); set => _value = value; diff --git a/Jint/Runtime/Descriptors/Specialized/ReflectionDescriptor.cs b/Jint/Runtime/Descriptors/Specialized/ReflectionDescriptor.cs index 353036fb28..d35d4eef7b 100644 --- a/Jint/Runtime/Descriptors/Specialized/ReflectionDescriptor.cs +++ b/Jint/Runtime/Descriptors/Specialized/ReflectionDescriptor.cs @@ -24,7 +24,7 @@ public ReflectionDescriptor( } - protected internal override JsValue CustomValue + protected internal override JsValue? CustomValue { get { @@ -35,7 +35,7 @@ protected internal override JsValue CustomValue { try { - _reflectionAccessor.SetValue(_engine, _target, value); + _reflectionAccessor.SetValue(_engine, _target, value!); } catch (TargetInvocationException exception) { @@ -44,4 +44,4 @@ protected internal override JsValue CustomValue } } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Environments/Binding.cs b/Jint/Runtime/Environments/Binding.cs index 70cf2c2f0b..b71163a506 100644 --- a/Jint/Runtime/Environments/Binding.cs +++ b/Jint/Runtime/Environments/Binding.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; using Jint.Native; namespace Jint.Runtime.Environments diff --git a/Jint/Runtime/Environments/DeclarativeEnvironmentRecord.cs b/Jint/Runtime/Environments/DeclarativeEnvironmentRecord.cs index 91cf686a1d..ff5ba07b12 100644 --- a/Jint/Runtime/Environments/DeclarativeEnvironmentRecord.cs +++ b/Jint/Runtime/Environments/DeclarativeEnvironmentRecord.cs @@ -1,4 +1,5 @@ -using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; using Jint.Collections; using Jint.Native; @@ -28,7 +29,7 @@ internal override bool TryGetBinding( in BindingName name, bool strict, out Binding binding, - out JsValue value) + [NotNullWhen(true)] out JsValue? value) { binding = default; var success = _dictionary.TryGetValue(name.Key, out binding); @@ -51,13 +52,13 @@ internal void CreateImmutableBindingAndInitialize(Key name, bool strict, JsValue public sealed override void CreateMutableBinding(string name, bool canBeDeleted = false) { _hasBindings = true; - _dictionary[name] = new Binding(null, canBeDeleted, mutable: true, strict: false); + _dictionary[name] = new Binding(null!, canBeDeleted, mutable: true, strict: false); } public sealed override void CreateImmutableBinding(string name, bool strict = true) { _hasBindings = true; - _dictionary[name] = new Binding(null, canBeDeleted: false, mutable: false, strict); + _dictionary[name] = new Binding(null!, canBeDeleted: false, mutable: false, strict); } public sealed override void InitializeBinding(string name, JsValue value) @@ -119,10 +120,10 @@ public override JsValue GetBindingValue(string name, bool strict) } ThrowUninitializedBindingError(name); - return null; + return null!; } - internal override bool TryGetBindingValue(string name, bool strict, out JsValue value) + internal override bool TryGetBindingValue(string name, bool strict, [NotNullWhen(true)] out JsValue? value) { _dictionary.TryGetValue(name, out var binding); if (binding.IsInitialized()) diff --git a/Jint/Runtime/Environments/EnvironmentRecord.cs b/Jint/Runtime/Environments/EnvironmentRecord.cs index 719585edd3..fc9fa84d28 100644 --- a/Jint/Runtime/Environments/EnvironmentRecord.cs +++ b/Jint/Runtime/Environments/EnvironmentRecord.cs @@ -1,6 +1,5 @@ -#nullable enable - using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using Jint.Native; namespace Jint.Runtime.Environments @@ -30,7 +29,7 @@ internal abstract bool TryGetBinding( in BindingName name, bool strict, out Binding binding, - out JsValue value); + [NotNullWhen(true)] out JsValue? value); /// /// Creates a new mutable binding in an environment record. @@ -80,7 +79,7 @@ internal abstract bool TryGetBinding( /// The value of an already existing binding from an environment record. /// True if the value is initialized, otherwise false. /// This is used for debugger inspection. Note that this will currently still throw if the binding cannot be retrieved (e.g. because it doesn't exist). - internal abstract bool TryGetBindingValue(string name, bool strict, out JsValue value); + internal abstract bool TryGetBindingValue(string name, bool strict, [NotNullWhen(true)] out JsValue? value); /// /// Delete a binding from an environment record. The String value N is the text of the bound name If a binding for N exists, remove the binding and return true. If the binding exists but cannot be removed return false. If the binding does not exist return true. @@ -107,7 +106,7 @@ public override object ToObject() return null; } - public override bool Equals(JsValue other) + public override bool Equals(JsValue? other) { ExceptionHelper.ThrowNotSupportedException(); return false; diff --git a/Jint/Runtime/Environments/ExecutionContext.cs b/Jint/Runtime/Environments/ExecutionContext.cs index d9df1a5cf0..119f615fac 100644 --- a/Jint/Runtime/Environments/ExecutionContext.cs +++ b/Jint/Runtime/Environments/ExecutionContext.cs @@ -1,6 +1,4 @@ -using Jint.Native.Function; - -#nullable enable +using Jint.Native.Function; namespace Jint.Runtime.Environments { @@ -39,7 +37,7 @@ public ExecutionContext UpdateVariableEnvironment(EnvironmentRecord variableEnvi return new ExecutionContext(ScriptOrModule, LexicalEnvironment, variableEnvironment, PrivateEnvironment, Realm, Function); } - public ExecutionContext UpdatePrivateEnvironment(PrivateEnvironmentRecord privateEnvironment) + public ExecutionContext UpdatePrivateEnvironment(PrivateEnvironmentRecord? privateEnvironment) { return new ExecutionContext(ScriptOrModule, LexicalEnvironment, VariableEnvironment, privateEnvironment, Realm, Function); } diff --git a/Jint/Runtime/Environments/FunctionEnvironmentRecord.cs b/Jint/Runtime/Environments/FunctionEnvironmentRecord.cs index 049f3e380f..5602619740 100644 --- a/Jint/Runtime/Environments/FunctionEnvironmentRecord.cs +++ b/Jint/Runtime/Environments/FunctionEnvironmentRecord.cs @@ -22,7 +22,7 @@ private enum ThisBindingStatus Uninitialized } - private JsValue _thisValue; + private JsValue? _thisValue; private ThisBindingStatus _thisBindingStatus; internal readonly FunctionInstance _functionObject; @@ -64,7 +64,7 @@ public override JsValue GetThisBinding() { if (_thisBindingStatus != ThisBindingStatus.Uninitialized) { - return _thisValue; + return _thisValue!; } var message = "Cannot access uninitialized 'this'"; @@ -91,7 +91,7 @@ public JsValue GetSuperBase() internal void InitializeParameters( Key[] parameterNames, bool hasDuplicates, - JsValue[] arguments) + JsValue[]? arguments) { var value = hasDuplicates ? Undefined : null; var directSet = !hasDuplicates && _dictionary.Count == 0; @@ -106,7 +106,7 @@ internal void InitializeParameters( parameterValue = (uint) i < (uint) arguments.Length ? arguments[i] : Undefined; } - _dictionary[paramName] = new Binding(parameterValue, canBeDeleted: false, mutable: true, strict: false); + _dictionary[paramName] = new Binding(parameterValue!, canBeDeleted: false, mutable: true, strict: false); } } } @@ -125,7 +125,7 @@ internal void AddFunctionParameters(EvaluationContext context, IFunction functio [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SetFunctionParameter( EvaluationContext context, - Node parameter, + Node? parameter, JsValue[] arguments, int index, bool initiallyEmpty) @@ -133,7 +133,7 @@ private void SetFunctionParameter( if (parameter is Identifier identifier) { var argument = (uint) index < (uint) arguments.Length ? arguments[index] : Undefined; - SetItemSafely(identifier.Name, argument, initiallyEmpty); + SetItemSafely(identifier.Name!, argument, initiallyEmpty); } else { @@ -143,7 +143,7 @@ private void SetFunctionParameter( private void SetFunctionParameterUnlikely( EvaluationContext context, - Node parameter, + Node? parameter, JsValue[] arguments, int index, bool initiallyEmpty) @@ -186,8 +186,7 @@ private void HandleObjectPattern(EvaluationContext context, bool initiallyEmpty, var argumentObject = argument.AsObject(); - var processedProperties = objectPattern.Properties.Count > 0 && - objectPattern.Properties[objectPattern.Properties.Count - 1] is RestElement + var processedProperties = objectPattern.Properties.Count > 0 && objectPattern.Properties[objectPattern.Properties.Count - 1] is RestElement ? new HashSet() : null; @@ -196,7 +195,7 @@ private void HandleObjectPattern(EvaluationContext context, bool initiallyEmpty, { var oldEnv = _engine.ExecutionContext.LexicalEnvironment; var paramVarEnv = JintEnvironment.NewDeclarativeEnvironment(_engine, oldEnv); - PrivateEnvironmentRecord privateEnvironment = null; // TODO PRIVATE check when implemented + PrivateEnvironmentRecord? privateEnvironment = null; // TODO PRIVATE check when implemented _engine.EnterExecutionContext(paramVarEnv, paramVarEnv, _engine.ExecutionContext.Realm, privateEnvironment); try @@ -206,7 +205,7 @@ private void HandleObjectPattern(EvaluationContext context, bool initiallyEmpty, JsString propertyName = JsString.Empty; if (p.Key is Identifier propertyIdentifier) { - propertyName = JsString.Create(propertyIdentifier.Name); + propertyName = JsString.Create(propertyIdentifier.Name!); } else if (p.Key is Literal propertyLiteral) { @@ -231,9 +230,9 @@ private void HandleObjectPattern(EvaluationContext context, bool initiallyEmpty, { if (((RestElement) property).Argument is Identifier restIdentifier) { - var rest = _engine.Realm.Intrinsics.Object.Construct(argumentObject.Properties.Count - processedProperties.Count); + var rest = _engine.Realm.Intrinsics.Object.Construct(argumentObject.Properties!.Count - processedProperties!.Count); argumentObject.CopyDataProperties(rest, processedProperties); - SetItemSafely(restIdentifier.Name, rest, initiallyEmpty); + SetItemSafely(restIdentifier.Name!, rest, initiallyEmpty); } else { @@ -257,7 +256,7 @@ private void HandleArrayPattern(EvaluationContext context, bool initiallyEmpty, ExceptionHelper.ThrowTypeError(_functionObject._realm, "Destructed parameter is null"); } - ArrayInstance array = null; + ArrayInstance? array = null; var arrayContents = System.Array.Empty(); if (argument.IsArray()) { @@ -313,7 +312,7 @@ private void HandleRestElementArray( if (restElement.Argument is Identifier restIdentifier) { - SetItemSafely(restIdentifier.Name, rest, initiallyEmpty); + SetItemSafely(restIdentifier.Name!, rest, initiallyEmpty); } else if (restElement.Argument is BindingPattern bindingPattern) { diff --git a/Jint/Runtime/Environments/GlobalEnvironmentRecord.cs b/Jint/Runtime/Environments/GlobalEnvironmentRecord.cs index c55ae5ffad..970590f149 100644 --- a/Jint/Runtime/Environments/GlobalEnvironmentRecord.cs +++ b/Jint/Runtime/Environments/GlobalEnvironmentRecord.cs @@ -1,4 +1,5 @@ -using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; using Jint.Native; using Jint.Native.Global; using Jint.Native.Object; @@ -35,7 +36,7 @@ internal override bool TryGetBinding( in BindingName name, bool strict, out Binding binding, - out JsValue value) + [NotNullWhen(true)] out JsValue? value) { if (_declarativeRecord._hasBindings && _declarativeRecord.TryGetBinding(name, strict, out binding, out value)) @@ -48,7 +49,7 @@ internal override bool TryGetBinding( value = default; // normal case is to find - if (_global._properties._dictionary.TryGetValue(name.Key, out var property) + if (_global._properties!._dictionary.TryGetValue(name.Key, out var property) && property != PropertyDescriptor.Undefined) { value = ObjectInstance.UnwrapJsValue(property, _global); @@ -61,7 +62,7 @@ internal override bool TryGetBinding( [MethodImpl(MethodImplOptions.NoInlining)] private bool TryGetBindingForGlobalParent( in BindingName name, - out JsValue value, + [NotNullWhen(true)] out JsValue? value, PropertyDescriptor property) { value = default; @@ -169,7 +170,7 @@ public override JsValue GetBindingValue(string name, bool strict) : _objectRecord.GetBindingValue(name, strict); } - internal override bool TryGetBindingValue(string name, bool strict, out JsValue value) + internal override bool TryGetBindingValue(string name, bool strict, [NotNullWhen(true)] out JsValue? value) { return _declarativeRecord._hasBindings && _declarativeRecord.HasBinding(name) ? _declarativeRecord.TryGetBindingValue(name, strict, out value) @@ -240,7 +241,7 @@ public bool HasRestrictedGlobalProperty(string name) public bool CanDeclareGlobalVar(string name) { - if (_global._properties.ContainsKey(name)) + if (_global._properties!.ContainsKey(name)) { return true; } @@ -250,7 +251,7 @@ public bool CanDeclareGlobalVar(string name) public bool CanDeclareGlobalFunction(string name) { - if (!_global._properties.TryGetValue(name, out var existingProp) + if (!_global._properties!.TryGetValue(name, out var existingProp) || existingProp == PropertyDescriptor.Undefined) { return _global.Extensible; @@ -311,7 +312,7 @@ internal override string[] GetAllBindingNames() .Concat(_declarativeRecord.GetAllBindingNames()).ToArray(); } - public override bool Equals(JsValue other) + public override bool Equals(JsValue? other) { return ReferenceEquals(_objectRecord, other); } diff --git a/Jint/Runtime/Environments/JintEnvironment.cs b/Jint/Runtime/Environments/JintEnvironment.cs index 735428299c..1eac7135b3 100644 --- a/Jint/Runtime/Environments/JintEnvironment.cs +++ b/Jint/Runtime/Environments/JintEnvironment.cs @@ -1,5 +1,4 @@ -#nullable enable - +using System.Diagnostics.CodeAnalysis; using Jint.Native; using Jint.Native.Function; using Jint.Native.Object; @@ -11,7 +10,7 @@ internal static class JintEnvironment internal static bool TryGetIdentifierEnvironmentWithBinding( EnvironmentRecord env, in EnvironmentRecord.BindingName name, - out EnvironmentRecord? record) + [NotNullWhen(true)] out EnvironmentRecord? record) { record = env; @@ -38,8 +37,8 @@ internal static bool TryGetIdentifierEnvironmentWithBindingValue( EnvironmentRecord env, in EnvironmentRecord.BindingName name, bool strict, - out EnvironmentRecord? record, - out JsValue? value) + [NotNullWhen(true)] out EnvironmentRecord? record, + [NotNullWhen(true)] out JsValue? value) { record = env; value = default; @@ -69,7 +68,7 @@ record = record._outerEnv; /// /// https://tc39.es/ecma262/#sec-newdeclarativeenvironment /// - internal static DeclarativeEnvironmentRecord NewDeclarativeEnvironment(Engine engine, EnvironmentRecord outer, bool catchEnvironment = false) + internal static DeclarativeEnvironmentRecord NewDeclarativeEnvironment(Engine engine, EnvironmentRecord? outer, bool catchEnvironment = false) { return new DeclarativeEnvironmentRecord(engine, catchEnvironment) { diff --git a/Jint/Runtime/Environments/ModuleEnvironmentRecord.cs b/Jint/Runtime/Environments/ModuleEnvironmentRecord.cs index 3864ddc23a..6f1c9d0ebd 100644 --- a/Jint/Runtime/Environments/ModuleEnvironmentRecord.cs +++ b/Jint/Runtime/Environments/ModuleEnvironmentRecord.cs @@ -1,4 +1,5 @@ -using Jint.Collections; +using System.Diagnostics.CodeAnalysis; +using Jint.Collections; using Jint.Native; using Jint.Runtime.Modules; @@ -47,7 +48,7 @@ public override JsValue GetBindingValue(string name, bool strict) return base.GetBindingValue(name, strict); } - internal override bool TryGetBinding(in BindingName name, bool strict, out Binding binding, out JsValue value) + internal override bool TryGetBinding(in BindingName name, bool strict, out Binding binding, [NotNullWhen(true)] out JsValue? value) { if (_importBindings.TryGetValue(name.Key, out var indirectBinding)) { @@ -65,4 +66,4 @@ internal override bool TryGetBinding(in BindingName name, bool strict, out Bindi public override bool HasThisBinding() => true; private readonly record struct IndirectBinding(ModuleRecord Module, string BindingName); -} \ No newline at end of file +} diff --git a/Jint/Runtime/Environments/ObjectEnvironmentRecord.cs b/Jint/Runtime/Environments/ObjectEnvironmentRecord.cs index 9a5ee154cc..4ed83d82a4 100644 --- a/Jint/Runtime/Environments/ObjectEnvironmentRecord.cs +++ b/Jint/Runtime/Environments/ObjectEnvironmentRecord.cs @@ -1,4 +1,5 @@ -using Jint.Native; +using System.Diagnostics.CodeAnalysis; +using Jint.Native; using Jint.Native.Object; using Jint.Native.Symbol; using Jint.Runtime.Descriptors; @@ -53,7 +54,7 @@ internal override bool TryGetBinding( in BindingName name, bool strict, out Binding binding, - out JsValue value) + [NotNullWhen(true)] out JsValue? value) { // we unwrap by name binding = default; @@ -141,7 +142,7 @@ internal override void SetMutableBinding(in BindingName name, JsValue value, boo { ExceptionHelper.ThrowReferenceNameError(_engine.Realm, name.Key); } - + _bindingObject.Set(name.StringValue, value); } @@ -156,7 +157,7 @@ public override JsValue GetBindingValue(string name, bool strict) return ObjectInstance.UnwrapJsValue(desc, _bindingObject); } - internal override bool TryGetBindingValue(string name, bool strict, out JsValue value) + internal override bool TryGetBindingValue(string name, bool strict, [NotNullWhen(true)] out JsValue? value) { var desc = _bindingObject.GetProperty(name); if (strict && desc == PropertyDescriptor.Undefined) @@ -188,17 +189,17 @@ internal override string[] GetAllBindingNames() return _bindingObject.GetOwnProperties().Select( x=> x.Key.ToString()).ToArray(); } - return System.Array.Empty(); + return Array.Empty(); } - public override bool Equals(JsValue other) + public override bool Equals(JsValue? other) { return ReferenceEquals(_bindingObject, other); } public override JsValue GetThisBinding() { - throw new System.NotImplementedException(); + throw new NotImplementedException(); } } } diff --git a/Jint/Runtime/Environments/PrivateEnvironmentRecord.cs b/Jint/Runtime/Environments/PrivateEnvironmentRecord.cs index 09bc13f1c7..e843b75424 100644 --- a/Jint/Runtime/Environments/PrivateEnvironmentRecord.cs +++ b/Jint/Runtime/Environments/PrivateEnvironmentRecord.cs @@ -5,12 +5,12 @@ namespace Jint.Runtime.Environments /// internal sealed class PrivateEnvironmentRecord { - private readonly PrivateEnvironmentRecord _outerPrivateEnvironment; + private readonly PrivateEnvironmentRecord? _outerPrivateEnvironment; private readonly List _names = new(); private readonly record struct PrivateName(string Name, string Description); - public PrivateEnvironmentRecord(PrivateEnvironmentRecord outerPrivEnv) + public PrivateEnvironmentRecord(PrivateEnvironmentRecord? outerPrivEnv) { _outerPrivateEnvironment = outerPrivEnv; } @@ -18,7 +18,7 @@ public PrivateEnvironmentRecord(PrivateEnvironmentRecord outerPrivEnv) /// /// https://tc39.es/ecma262/#sec-resolve-private-identifier /// - public string ResolvePrivateIdentifier(string identifier) + public string? ResolvePrivateIdentifier(string identifier) { var names = _names; foreach (var privateName in names) @@ -29,7 +29,7 @@ public string ResolvePrivateIdentifier(string identifier) } } - return _outerPrivateEnvironment.ResolvePrivateIdentifier(identifier); + return _outerPrivateEnvironment?.ResolvePrivateIdentifier(identifier); } } } diff --git a/Jint/Runtime/ExceptionHelper.cs b/Jint/Runtime/ExceptionHelper.cs index 74f3b7e082..66a78a0b07 100644 --- a/Jint/Runtime/ExceptionHelper.cs +++ b/Jint/Runtime/ExceptionHelper.cs @@ -1,4 +1,4 @@ -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.ExceptionServices; using Esprima; @@ -13,7 +13,7 @@ namespace Jint.Runtime internal static class ExceptionHelper { [DoesNotReturn] - public static void ThrowSyntaxError(Realm realm, string message = null) + public static void ThrowSyntaxError(Realm realm, string? message = null) { throw new JavaScriptException(realm.Intrinsics.SyntaxError, message); } @@ -25,13 +25,13 @@ public static void ThrowSyntaxError(Realm realm, string message, Location locati } [DoesNotReturn] - public static void ThrowArgumentException(string message = null) + public static void ThrowArgumentException(string? message = null) { ThrowArgumentException(message, null); } [DoesNotReturn] - public static void ThrowArgumentException(string message, string paramName) + public static void ThrowArgumentException(string? message, string? paramName) { throw new ArgumentException(message, paramName); } @@ -43,32 +43,32 @@ public static void ThrowReferenceError(Realm realm, Reference reference) } [DoesNotReturn] - public static void ThrowReferenceNameError(Realm realm, string name) + public static void ThrowReferenceNameError(Realm realm, string? name) { var message = name != null ? name + " is not defined" : null; ThrowReferenceError(realm, message); } [DoesNotReturn] - public static void ThrowReferenceError(Realm realm, string message) + public static void ThrowReferenceError(Realm realm, string? message) { throw new JavaScriptException(realm.Intrinsics.ReferenceError, message); } [DoesNotReturn] - public static void ThrowTypeErrorNoEngine(string message = null) + public static void ThrowTypeErrorNoEngine(string? message = null) { throw new TypeErrorException(message); } [DoesNotReturn] - public static void ThrowTypeError(Realm realm, string message = null) + public static void ThrowTypeError(Realm realm, string? message = null) { throw new JavaScriptException(realm.Intrinsics.TypeError, message); } [DoesNotReturn] - public static void ThrowRangeError(Realm realm, string message = null) + public static void ThrowRangeError(Realm realm, string? message = null) { throw new JavaScriptException(realm.Intrinsics.RangeError, message); } @@ -80,7 +80,7 @@ public static void ThrowUriError(Realm realm) } [DoesNotReturn] - public static void ThrowNotImplementedException(string message = null) + public static void ThrowNotImplementedException(string? message = null) { throw new NotImplementedException(message); } @@ -110,13 +110,13 @@ public static void ThrowArgumentOutOfRangeException() } [DoesNotReturn] - public static void ThrowNotSupportedException(string message = null) + public static void ThrowNotSupportedException(string? message = null) { throw new NotSupportedException(message); } [DoesNotReturn] - public static void ThrowInvalidOperationException(string message = null, Exception exception = null) + public static void ThrowInvalidOperationException(string? message = null, Exception? exception = null) { throw new InvalidOperationException(message, exception); } @@ -175,7 +175,9 @@ public static void ThrowMeaningfulException(Engine engine, TargetInvocationExcep } ExceptionDispatchInfo.Capture(meaningfulException).Throw(); +#pragma warning disable CS8763 } +#pragma warning restore CS8763 [DoesNotReturn] internal static void ThrowError(Engine engine, string message) @@ -202,7 +204,7 @@ public static void ThrowExecutionCanceledException() } [DoesNotReturn] - public static void ThrowModuleResolutionException(string resolverAlgorithmError, string specifier, string parent) + public static void ThrowModuleResolutionException(string resolverAlgorithmError, string specifier, string? parent) { throw new ModuleResolutionException(resolverAlgorithmError, specifier, parent); } diff --git a/Jint/Runtime/ExecutionCanceledException.cs b/Jint/Runtime/ExecutionCanceledException.cs index a595a2ea93..9948f40f1a 100644 --- a/Jint/Runtime/ExecutionCanceledException.cs +++ b/Jint/Runtime/ExecutionCanceledException.cs @@ -1,4 +1,4 @@ -namespace Jint.Runtime +namespace Jint.Runtime { public sealed class ExecutionCanceledException : JintException { @@ -6,4 +6,4 @@ public ExecutionCanceledException() : base("The script execution was canceled.") { } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/ExecutionContextStack.cs b/Jint/Runtime/ExecutionContextStack.cs index dd426c962c..3066598465 100644 --- a/Jint/Runtime/ExecutionContextStack.cs +++ b/Jint/Runtime/ExecutionContextStack.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Runtime.CompilerServices; using Jint.Collections; using Jint.Runtime.Environments; @@ -29,7 +27,7 @@ public void ReplaceTopVariableEnvironment(EnvironmentRecord newEnv) array[size - 1] = array[size - 1].UpdateVariableEnvironment(newEnv); } - public void ReplaceTopPrivateEnvironment(PrivateEnvironmentRecord newEnv) + public void ReplaceTopPrivateEnvironment(PrivateEnvironmentRecord? newEnv) { var array = _stack._array; var size = _stack._size; diff --git a/Jint/Runtime/Host.cs b/Jint/Runtime/Host.cs index 07be69d551..572891ac29 100644 --- a/Jint/Runtime/Host.cs +++ b/Jint/Runtime/Host.cs @@ -1,5 +1,3 @@ -#nullable enable - using Jint.Native; using Jint.Native.Global; using Jint.Native.Object; @@ -91,7 +89,7 @@ protected internal virtual Realm CreateRealm() realmRec.GlobalEnv = globalEnv; realmRec.GlobalObject = globalObject; - Engine._realmInConstruction = null; + Engine._realmInConstruction = null!; return realmRec; } @@ -156,7 +154,7 @@ internal virtual void FinishDynamicImport(IScriptOrModule? referencingModule, st } catch (JavaScriptException ex) { - promiseCapability.Reject.Call(JsValue.Undefined, new [] { ex.Error }); + promiseCapability.Reject.Call(JsValue.Undefined, new [] { ex.Error! }); } return JsValue.Undefined; }, 0, PropertyFlag.Configurable); diff --git a/Jint/Runtime/IScriptOrModule.Extensions.cs b/Jint/Runtime/IScriptOrModule.Extensions.cs index 3da6a09090..c60a4ef4a9 100644 --- a/Jint/Runtime/IScriptOrModule.Extensions.cs +++ b/Jint/Runtime/IScriptOrModule.Extensions.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima; using Jint.Runtime.Modules; diff --git a/Jint/Runtime/Interop/ClrFunctionInstance.cs b/Jint/Runtime/Interop/ClrFunctionInstance.cs index b7d84fd055..982f44cc1e 100644 --- a/Jint/Runtime/Interop/ClrFunctionInstance.cs +++ b/Jint/Runtime/Interop/ClrFunctionInstance.cs @@ -1,4 +1,4 @@ -using Jint.Native; +using Jint.Native; using Jint.Native.Function; using Jint.Runtime.Descriptors; @@ -9,7 +9,7 @@ namespace Jint.Runtime.Interop /// public sealed class ClrFunctionInstance : FunctionInstance, IEquatable { - private readonly string _name; + private readonly string? _name; internal readonly Func _func; public ClrFunctionInstance( @@ -32,12 +32,12 @@ public ClrFunctionInstance( protected internal override JsValue Call(JsValue thisObject, JsValue[] arguments) => _func(thisObject, arguments); - public override bool Equals(JsValue obj) + public override bool Equals(JsValue? obj) { return Equals(obj as ClrFunctionInstance); } - public bool Equals(ClrFunctionInstance other) + public bool Equals(ClrFunctionInstance? other) { if (ReferenceEquals(null, other)) { diff --git a/Jint/Runtime/Interop/DefaultObjectConverter.cs b/Jint/Runtime/Interop/DefaultObjectConverter.cs index 838a534c33..ce12ac553a 100644 --- a/Jint/Runtime/Interop/DefaultObjectConverter.cs +++ b/Jint/Runtime/Interop/DefaultObjectConverter.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using System.Threading; using Jint.Native; using Jint.Native.Array; @@ -33,7 +34,7 @@ internal static class DefaultObjectConverter } }; - public static bool TryConvert(Engine engine, object value, out JsValue result) + public static bool TryConvert(Engine engine, object value, [NotNullWhen(true)] out JsValue? result) { result = null; var valueType = value.GetType(); @@ -111,7 +112,7 @@ public static bool TryConvert(Engine engine, object value, out JsValue result) return result is not null; } - private static bool TryConvertConvertible(Engine engine, IConvertible convertible, out JsValue result) + private static bool TryConvertConvertible(Engine engine, IConvertible convertible, [NotNullWhen(true)] out JsValue? result) { result = convertible.GetTypeCode() switch { diff --git a/Jint/Runtime/Interop/DefaultTypeConverter.cs b/Jint/Runtime/Interop/DefaultTypeConverter.cs index 6055a4e72b..37d89ca077 100644 --- a/Jint/Runtime/Interop/DefaultTypeConverter.cs +++ b/Jint/Runtime/Interop/DefaultTypeConverter.cs @@ -1,5 +1,6 @@ using System.Collections.Concurrent; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; using Jint.Extensions; @@ -17,7 +18,7 @@ public class DefaultTypeConverter : ITypeConverter private readonly record struct TypeConversionKey(Type Source, Type Target); private static readonly ConcurrentDictionary _knownConversions = new(); - private static readonly ConcurrentDictionary _knownCastOperators = new(); + private static readonly ConcurrentDictionary _knownCastOperators = new(); private static readonly Type intType = typeof(int); private static readonly Type iCallableType = typeof(Func); @@ -36,7 +37,7 @@ public DefaultTypeConverter(Engine engine) _engine = engine; } - public virtual object Convert(object value, Type type, IFormatProvider formatProvider) + public virtual object? Convert(object? value, Type type, IFormatProvider formatProvider) { if (value == null) { @@ -91,7 +92,7 @@ public virtual object Convert(object value, Type type, IFormatProvider formatPro var func = (Func) value; var functionInstance = func.Target as FunctionInstance; - Delegate d = functionInstance?.GetHiddenClrObjectProperty(delegatePropertyKey) as Delegate; + var d = functionInstance?.GetHiddenClrObjectProperty(delegatePropertyKey) as Delegate; if (d is null) { @@ -112,7 +113,7 @@ public virtual object Convert(object value, Type type, IFormatProvider formatPro } var targetElementType = type.GetElementType(); - var itemsConverted = new object[source.Length]; + var itemsConverted = new object?[source.Length]; for (var i = 0; i < source.Length; i++) { itemsConverted[i] = Convert(source[i], targetElementType, formatProvider); @@ -254,11 +255,11 @@ private Delegate BuildDelegate(Type type, Func func new ReadOnlyCollection(parameters)).Compile(); } - private bool TryCastWithOperators(object value, Type type, Type valueType, out object converted) + private bool TryCastWithOperators(object value, Type type, Type valueType, [NotNullWhen(true)] out object? converted) { var key = new TypeConversionKey(valueType, type); - static MethodInfo CreateValueFactory(TypeConversionKey k) + static MethodInfo? CreateValueFactory(TypeConversionKey k) { var (source, target) = k; foreach (var m in source.GetOperatorOverloadMethods().Concat(target.GetOperatorOverloadMethods())) @@ -301,9 +302,9 @@ static MethodInfo CreateValueFactory(TypeConversionKey k) return false; } - public virtual bool TryConvert(object value, Type type, IFormatProvider formatProvider, out object converted) + public virtual bool TryConvert(object? value, Type type, IFormatProvider formatProvider, out object? converted) { - var key = new TypeConversionKey(value?.GetType(), type); + var key = new TypeConversionKey(value?.GetType() ?? typeof(void), type); // string conversion is not stable, "filter" -> int is invalid, "0" -> int is valid var canConvert = value is string || _knownConversions.GetOrAdd(key, _ => @@ -340,7 +341,7 @@ public virtual bool TryConvert(object value, Type type, IFormatProvider formatPr internal static class ObjectExtensions { - public static object GetHiddenClrObjectProperty(this ObjectInstance obj, string name) + public static object? GetHiddenClrObjectProperty(this ObjectInstance obj, string name) { return (obj.Get(name) as IObjectWrapper)?.Target; } diff --git a/Jint/Runtime/Interop/DelegateWrapper.cs b/Jint/Runtime/Interop/DelegateWrapper.cs index c03b84d505..5627ffc240 100644 --- a/Jint/Runtime/Interop/DelegateWrapper.cs +++ b/Jint/Runtime/Interop/DelegateWrapper.cs @@ -58,14 +58,14 @@ protected internal override JsValue Call(JsValue thisObject, JsValue[] jsArgumen var clrTypeConverter = Engine.ClrTypeConverter; var valueCoercionType = Engine.Options.Interop.ValueCoercion; - var parameters = new object[delegateArgumentsCount]; + var parameters = new object?[delegateArgumentsCount]; // convert non params parameter to expected types for (var i = 0; i < jsArgumentsWithoutParamsCount; i++) { var parameterType = parameterInfos[i].ParameterType; var value = jsArguments[i]; - object converted; + object? converted; if (parameterType == typeof(JsValue)) { @@ -108,7 +108,7 @@ protected internal override JsValue Call(JsValue thisObject, JsValue[] jsArgumen { var paramsIndex = i - paramsArgumentIndex; var value = jsArguments[i]; - object converted; + object? converted; if (paramsParameterType == typeof(JsValue)) { diff --git a/Jint/Runtime/Interop/GetterFunctionInstance.cs b/Jint/Runtime/Interop/GetterFunctionInstance.cs index b6fabcb87b..4cb3df9b56 100644 --- a/Jint/Runtime/Interop/GetterFunctionInstance.cs +++ b/Jint/Runtime/Interop/GetterFunctionInstance.cs @@ -1,4 +1,4 @@ -using Jint.Native; +using Jint.Native; using Jint.Native.Function; namespace Jint.Runtime.Interop diff --git a/Jint/Runtime/Interop/IObjectConverter.cs b/Jint/Runtime/Interop/IObjectConverter.cs index 8ab6571ef8..5b9fd11d9a 100644 --- a/Jint/Runtime/Interop/IObjectConverter.cs +++ b/Jint/Runtime/Interop/IObjectConverter.cs @@ -1,4 +1,5 @@ -using Jint.Native; +using System.Diagnostics.CodeAnalysis; +using Jint.Native; namespace Jint.Runtime.Interop { @@ -7,6 +8,6 @@ namespace Jint.Runtime.Interop /// public interface IObjectConverter { - bool TryConvert(Engine engine, object value, out JsValue result); + bool TryConvert(Engine engine, object value, [NotNullWhen(true)] out JsValue? result); } } diff --git a/Jint/Runtime/Interop/IObjectWrapper.cs b/Jint/Runtime/Interop/IObjectWrapper.cs index cbc3d44c5b..cdc88ede8e 100644 --- a/Jint/Runtime/Interop/IObjectWrapper.cs +++ b/Jint/Runtime/Interop/IObjectWrapper.cs @@ -1,4 +1,4 @@ -namespace Jint.Runtime.Interop +namespace Jint.Runtime.Interop { public interface IObjectWrapper { diff --git a/Jint/Runtime/Interop/IReferenceResolver.cs b/Jint/Runtime/Interop/IReferenceResolver.cs index cea6be69c6..b2f163b390 100644 --- a/Jint/Runtime/Interop/IReferenceResolver.cs +++ b/Jint/Runtime/Interop/IReferenceResolver.cs @@ -1,4 +1,4 @@ -using Jint.Native; +using Jint.Native; using Jint.Runtime.References; namespace Jint.Runtime.Interop @@ -52,4 +52,4 @@ public interface IReferenceResolver /// Whether to accept the value. bool CheckCoercible(JsValue value); } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interop/ITypeConverter.cs b/Jint/Runtime/Interop/ITypeConverter.cs index afa4f1c3da..8449edc5b3 100644 --- a/Jint/Runtime/Interop/ITypeConverter.cs +++ b/Jint/Runtime/Interop/ITypeConverter.cs @@ -1,8 +1,8 @@ -namespace Jint.Runtime.Interop +namespace Jint.Runtime.Interop { public interface ITypeConverter { - object Convert(object value, Type type, IFormatProvider formatProvider); - bool TryConvert(object value, Type type, IFormatProvider formatProvider, out object converted); + object? Convert(object? value, Type type, IFormatProvider formatProvider); + bool TryConvert(object? value, Type type, IFormatProvider formatProvider, out object? converted); } } diff --git a/Jint/Runtime/Interop/MethodDescriptor.cs b/Jint/Runtime/Interop/MethodDescriptor.cs index 2fc2885c08..152c9de2e3 100644 --- a/Jint/Runtime/Interop/MethodDescriptor.cs +++ b/Jint/Runtime/Interop/MethodDescriptor.cs @@ -101,11 +101,11 @@ static int CreateComparison(MethodDescriptor d1, MethodDescriptor d2) return descriptors; } - public JsValue Call(Engine _engine, object instance, JsValue[] arguments) + public JsValue Call(Engine engine, object? instance, JsValue[] arguments) { - var parameters = new object[arguments.Length]; + var parameters = new object?[arguments.Length]; var methodParameters = Parameters; - var valueCoercionType = _engine.Options.Interop.ValueCoercion; + var valueCoercionType = engine.Options.Interop.ValueCoercion; try { @@ -113,7 +113,7 @@ public JsValue Call(Engine _engine, object instance, JsValue[] arguments) { var parameterType = methodParameters[i].ParameterType; var value = arguments[i]; - object converted; + object? converted; if (typeof(JsValue).IsAssignableFrom(parameterType)) { @@ -121,7 +121,7 @@ public JsValue Call(Engine _engine, object instance, JsValue[] arguments) } else if (!ReflectionExtensions.TryConvertViaTypeCoercion(parameterType, valueCoercionType, value, out converted)) { - converted = _engine.ClrTypeConverter.Convert( + converted = engine.ClrTypeConverter.Convert( value.ToObject(), parameterType, System.Globalization.CultureInfo.InvariantCulture); @@ -133,12 +133,12 @@ public JsValue Call(Engine _engine, object instance, JsValue[] arguments) if (Method is MethodInfo m) { var retVal = m.Invoke(instance, parameters); - return JsValue.FromObject(_engine, retVal); + return JsValue.FromObject(engine, retVal); } else if (Method is ConstructorInfo c) { var retVal = c.Invoke(parameters); - return JsValue.FromObject(_engine, retVal); + return JsValue.FromObject(engine, retVal); } else { @@ -147,7 +147,7 @@ public JsValue Call(Engine _engine, object instance, JsValue[] arguments) } catch (TargetInvocationException exception) { - ExceptionHelper.ThrowMeaningfulException(_engine, exception); + ExceptionHelper.ThrowMeaningfulException(engine, exception); return null; } } diff --git a/Jint/Runtime/Interop/MethodInfoFunctionInstance.cs b/Jint/Runtime/Interop/MethodInfoFunctionInstance.cs index 2546c794f8..3ad902ac52 100644 --- a/Jint/Runtime/Interop/MethodInfoFunctionInstance.cs +++ b/Jint/Runtime/Interop/MethodInfoFunctionInstance.cs @@ -11,7 +11,7 @@ internal sealed class MethodInfoFunctionInstance : FunctionInstance { private static readonly JsString _name = new JsString("Function"); private readonly MethodDescriptor[] _methods; - private readonly ClrFunctionInstance _fallbackClrFunctionInstance; + private readonly ClrFunctionInstance? _fallbackClrFunctionInstance; public MethodInfoFunctionInstance(Engine engine, MethodDescriptor[] methods) : base(engine, engine.Realm, _name) @@ -101,7 +101,7 @@ private static MethodBase ResolveMethod(MethodBase method, ParameterInfo[] metho { return method; } - MethodInfo methodInfo = method as MethodInfo; + var methodInfo = method as MethodInfo; if (methodInfo == null) { // probably should issue at least a warning here @@ -154,7 +154,7 @@ JsValue[] ArgumentProvider(MethodDescriptor method) var converter = Engine.ClrTypeConverter; var thisObj = thisObject.ToObject(); - object[] parameters = null; + object?[]? parameters = null; foreach (var (method, arguments, _) in TypeConverter.FindBestMatch(_engine, _methods, ArgumentProvider)) { var methodParameters = method.Parameters; diff --git a/Jint/Runtime/Interop/NamespaceReference.cs b/Jint/Runtime/Interop/NamespaceReference.cs index 1dadcb7dbc..3a657598db 100644 --- a/Jint/Runtime/Interop/NamespaceReference.cs +++ b/Jint/Runtime/Interop/NamespaceReference.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using System.Reflection; using Jint.Native; using Jint.Native.Object; @@ -153,13 +153,13 @@ public JsValue GetPath(string path) /// Name of the type. /// /// The type. - private static Type GetType(Assembly assembly, string typeName) + private static Type? GetType(Assembly assembly, string typeName) { var compared = typeName.Replace("+", "."); Type[] types = assembly.GetTypes(); foreach (Type t in types) { - if (t.FullName.Replace("+", ".") == compared) + if (t.FullName?.Replace("+", ".") == compared) { return t; } diff --git a/Jint/Runtime/Interop/ObjectWrapper.cs b/Jint/Runtime/Interop/ObjectWrapper.cs index 1b82f874ea..777eead7c1 100644 --- a/Jint/Runtime/Interop/ObjectWrapper.cs +++ b/Jint/Runtime/Interop/ObjectWrapper.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Collections; using System.Globalization; using System.Reflection; @@ -146,7 +144,7 @@ private IEnumerable EnumerateOwnPropertyKeys(Types types) if (stringKey is not null || _engine.ClrTypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out stringKey)) { - var jsString = JsString.Create((string) stringKey); + var jsString = JsString.Create((string) stringKey!); yield return jsString; } } @@ -254,7 +252,7 @@ private static JsValue Iterator(JsValue thisObj, JsValue[] arguments) private static JsValue GetLength(JsValue thisObj, JsValue[] arguments) { var wrapper = (ObjectWrapper) thisObj; - return JsNumber.Create((int) wrapper._typeDescriptor.LengthProperty.GetValue(wrapper.Target)); + return JsNumber.Create((int) (wrapper._typeDescriptor.LengthProperty?.GetValue(wrapper.Target) ?? 0)); } internal override ulong GetSmallestIndex(ulong length) diff --git a/Jint/Runtime/Interop/Reflection/ConstantValueAccessor.cs b/Jint/Runtime/Interop/Reflection/ConstantValueAccessor.cs index 6dab975884..d6d60d785b 100644 --- a/Jint/Runtime/Interop/Reflection/ConstantValueAccessor.cs +++ b/Jint/Runtime/Interop/Reflection/ConstantValueAccessor.cs @@ -7,29 +7,29 @@ internal sealed class ConstantValueAccessor : ReflectionAccessor { public static readonly ConstantValueAccessor NullAccessor = new(null); - public ConstantValueAccessor(JsValue value) : base(null, null) + public ConstantValueAccessor(JsValue? value) : base(null!, null!) { ConstantValue = value; } public override bool Writable => false; - protected override JsValue ConstantValue { get; } + protected override JsValue? ConstantValue { get; } - protected override object DoGetValue(object target) + protected override object? DoGetValue(object target) { return ConstantValue; } - protected override void DoSetValue(object target, object value) + protected override void DoSetValue(object target, object? value) { throw new InvalidOperationException(); } public override PropertyDescriptor CreatePropertyDescriptor(Engine engine, object target, bool enumerable = true) { - return ConstantValue is null - ? PropertyDescriptor.Undefined + return ConstantValue is null + ? PropertyDescriptor.Undefined : new(ConstantValue, PropertyFlag.AllForbidden); } } diff --git a/Jint/Runtime/Interop/Reflection/DynamicObjectAccessor.cs b/Jint/Runtime/Interop/Reflection/DynamicObjectAccessor.cs index 306f48d213..9338f9d6cc 100644 --- a/Jint/Runtime/Interop/Reflection/DynamicObjectAccessor.cs +++ b/Jint/Runtime/Interop/Reflection/DynamicObjectAccessor.cs @@ -7,13 +7,13 @@ namespace Jint.Runtime.Interop.Reflection internal sealed class DynamicObjectAccessor : ReflectionAccessor { private readonly string _memberName; - private JintSetMemberBinder _setter; - private JintGetMemberBinder _getter; + private JintSetMemberBinder? _setter; + private JintGetMemberBinder? _getter; public DynamicObjectAccessor( Type memberType, string memberName, - PropertyInfo indexer = null) : base(memberType, memberName, indexer) + PropertyInfo? indexer = null) : base(memberType, memberName, indexer) { _memberName = memberName; } @@ -28,14 +28,14 @@ protected override object DoGetValue(object target) return result; } - protected override void DoSetValue(object target, object value) + protected override void DoSetValue(object target, object? value) { var dynamicObject = (DynamicObject) target; var setter = _setter ??= new JintSetMemberBinder(_memberName, ignoreCase: true); dynamicObject.TrySetMember(setter, value); } - protected override object ConvertValueToSet(Engine engine, object value) + protected override object? ConvertValueToSet(Engine engine, object value) { // we expect value to be generally CLR type, convert when possible return value switch diff --git a/Jint/Runtime/Interop/Reflection/FieldAccessor.cs b/Jint/Runtime/Interop/Reflection/FieldAccessor.cs index 1d786927e9..62804eb49e 100644 --- a/Jint/Runtime/Interop/Reflection/FieldAccessor.cs +++ b/Jint/Runtime/Interop/Reflection/FieldAccessor.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; namespace Jint.Runtime.Interop.Reflection { @@ -6,7 +6,7 @@ internal sealed class FieldAccessor : ReflectionAccessor { private readonly FieldInfo _fieldInfo; - public FieldAccessor(FieldInfo fieldInfo, string memberName = null, PropertyInfo indexer = null) + public FieldAccessor(FieldInfo fieldInfo, string? memberName = null, PropertyInfo? indexer = null) : base(fieldInfo.FieldType, memberName, indexer) { _fieldInfo = fieldInfo; @@ -19,9 +19,9 @@ protected override object DoGetValue(object target) return _fieldInfo.GetValue(target); } - protected override void DoSetValue(object target, object value) + protected override void DoSetValue(object target, object? value) { _fieldInfo.SetValue(target, value); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interop/Reflection/IndexerAccessor.cs b/Jint/Runtime/Interop/Reflection/IndexerAccessor.cs index 59d663a60e..24df1dc99d 100644 --- a/Jint/Runtime/Interop/Reflection/IndexerAccessor.cs +++ b/Jint/Runtime/Interop/Reflection/IndexerAccessor.cs @@ -1,4 +1,5 @@ using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using Jint.Native; @@ -14,11 +15,11 @@ internal sealed class IndexerAccessor : ReflectionAccessor private readonly PropertyInfo _indexer; private readonly MethodInfo _getter; private readonly MethodInfo _setter; - private readonly MethodInfo _containsKey; + private readonly MethodInfo? _containsKey; private static readonly PropertyInfo _iListIndexer = typeof(IList).GetProperty("Item"); - private IndexerAccessor(PropertyInfo indexer, MethodInfo containsKey, object key) + private IndexerAccessor(PropertyInfo indexer, MethodInfo? containsKey, object key) : base(indexer.PropertyType, key) { _indexer = indexer; @@ -33,14 +34,14 @@ internal static bool TryFindIndexer( Engine engine, Type targetType, string propertyName, - out IndexerAccessor indexerAccessor, - out PropertyInfo indexer) + [NotNullWhen(true)] out IndexerAccessor? indexerAccessor, + [NotNullWhen(true)] out PropertyInfo? indexer) { var paramTypeArray = new Type[1]; - IndexerAccessor ComposeIndexerFactory(PropertyInfo candidate, Type paramType) + IndexerAccessor? ComposeIndexerFactory(PropertyInfo candidate, Type paramType) { - object key = null; + object? key = null; // int key is quite common case if (paramType == typeof(int)) { @@ -141,15 +142,15 @@ protected override object DoGetValue(object target) return _getter.Invoke(target, parameters); } - protected override void DoSetValue(object target, object value) + protected override void DoSetValue(object target, object? value) { if (_setter is null) { ExceptionHelper.ThrowInvalidOperationException("Indexer has no public setter."); } - object[] parameters = { _key, value }; - _setter!.Invoke(target, parameters); + object?[] parameters = { _key, value }; + _setter.Invoke(target, parameters); } public override PropertyDescriptor CreatePropertyDescriptor(Engine engine, object target, bool enumerable = true) diff --git a/Jint/Runtime/Interop/Reflection/MethodAccessor.cs b/Jint/Runtime/Interop/Reflection/MethodAccessor.cs index ad7fb7883b..601e914dc0 100644 --- a/Jint/Runtime/Interop/Reflection/MethodAccessor.cs +++ b/Jint/Runtime/Interop/Reflection/MethodAccessor.cs @@ -6,19 +6,19 @@ internal sealed class MethodAccessor : ReflectionAccessor { private readonly MethodDescriptor[] _methods; - public MethodAccessor(MethodDescriptor[] methods) : base(null, null) + public MethodAccessor(MethodDescriptor[] methods) : base(null!, null!) { _methods = methods; } public override bool Writable => false; - protected override object DoGetValue(object target) + protected override object? DoGetValue(object target) { return null; } - protected override void DoSetValue(object target, object value) + protected override void DoSetValue(object target, object? value) { } diff --git a/Jint/Runtime/Interop/Reflection/PropertyAccessor.cs b/Jint/Runtime/Interop/Reflection/PropertyAccessor.cs index 5bacc6047b..72d253499d 100644 --- a/Jint/Runtime/Interop/Reflection/PropertyAccessor.cs +++ b/Jint/Runtime/Interop/Reflection/PropertyAccessor.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; namespace Jint.Runtime.Interop.Reflection { @@ -9,7 +9,7 @@ internal sealed class PropertyAccessor : ReflectionAccessor public PropertyAccessor( string memberName, PropertyInfo propertyInfo, - PropertyInfo indexerToTry = null) + PropertyInfo? indexerToTry = null) : base(propertyInfo.PropertyType, memberName, indexerToTry) { _propertyInfo = propertyInfo; @@ -22,9 +22,9 @@ protected override object DoGetValue(object target) return _propertyInfo.GetValue(target, index: null); } - protected override void DoSetValue(object target, object value) + protected override void DoSetValue(object target, object? value) { _propertyInfo.SetValue(target, value, index: null); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs b/Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs index 5a8fc05f65..d626bc90f2 100644 --- a/Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs +++ b/Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs @@ -13,13 +13,13 @@ namespace Jint.Runtime.Interop.Reflection internal abstract class ReflectionAccessor { private readonly Type _memberType; - private readonly object _memberName; - private readonly PropertyInfo _indexer; + private readonly object? _memberName; + private readonly PropertyInfo? _indexer; protected ReflectionAccessor( Type memberType, - object memberName, - PropertyInfo indexer = null) + object? memberName, + PropertyInfo? indexer = null) { _memberType = memberType; _memberName = memberName; @@ -28,11 +28,11 @@ protected ReflectionAccessor( public abstract bool Writable { get; } - protected abstract object DoGetValue(object target); + protected abstract object? DoGetValue(object target); - protected abstract void DoSetValue(object target, object value); + protected abstract void DoSetValue(object target, object? value); - public object GetValue(Engine engine, object target) + public object? GetValue(Engine engine, object target) { var constantValue = ConstantValue; if (constantValue is not null) @@ -58,9 +58,9 @@ public object GetValue(Engine engine, object target) return value; } - protected virtual JsValue ConstantValue => null; + protected virtual JsValue? ConstantValue => null; - private object TryReadFromIndexer(object target) + private object? TryReadFromIndexer(object target) { var getter = _indexer?.GetGetMethod(); if (getter is null) @@ -70,7 +70,7 @@ private object TryReadFromIndexer(object target) try { - object[] parameters = { _memberName }; + object[] parameters = { _memberName! }; return getter.Invoke(target, parameters); } catch @@ -81,7 +81,7 @@ private object TryReadFromIndexer(object target) public void SetValue(Engine engine, object target, JsValue value) { - object converted = null; + object? converted; if (_memberType == typeof(JsValue)) { converted = value; @@ -106,7 +106,7 @@ public void SetValue(Engine engine, object target, JsValue value) } } - protected virtual object ConvertValueToSet(Engine engine, object value) + protected virtual object? ConvertValueToSet(Engine engine, object value) { return engine.ClrTypeConverter.Convert(value, _memberType, CultureInfo.InvariantCulture); } diff --git a/Jint/Runtime/Interop/SetterFunctionInstance.cs b/Jint/Runtime/Interop/SetterFunctionInstance.cs index c4dc004e86..925aad1073 100644 --- a/Jint/Runtime/Interop/SetterFunctionInstance.cs +++ b/Jint/Runtime/Interop/SetterFunctionInstance.cs @@ -1,4 +1,4 @@ -using Jint.Native; +using Jint.Native; using Jint.Native.Function; namespace Jint.Runtime.Interop diff --git a/Jint/Runtime/Interop/TypeDescriptor.cs b/Jint/Runtime/Interop/TypeDescriptor.cs index 1d3339e86b..e1a1d0c8e4 100644 --- a/Jint/Runtime/Interop/TypeDescriptor.cs +++ b/Jint/Runtime/Interop/TypeDescriptor.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace Jint.Runtime.Interop @@ -10,9 +11,9 @@ internal sealed class TypeDescriptor private static readonly Type _genericDictionaryType = typeof(IDictionary<,>); private static readonly Type _stringType = typeof(string); - private readonly MethodInfo _tryGetValueMethod; - private readonly PropertyInfo _keysAccessor; - private readonly Type _valueType; + private readonly MethodInfo? _tryGetValueMethod; + private readonly PropertyInfo? _keysAccessor; + private readonly Type? _valueType; private TypeDescriptor(Type type) { @@ -49,7 +50,7 @@ private TypeDescriptor(Type type) public bool IsDictionary { get; } public bool IsStringKeyedGenericDictionary => _tryGetValueMethod is not null; public bool IsEnumerable { get; } - public PropertyInfo LengthProperty { get; } + public PropertyInfo? LengthProperty { get; } public bool Iterable => IsArrayLike || IsDictionary || IsEnumerable; @@ -82,7 +83,7 @@ private static bool DetermineIfObjectIsArrayLikeClrCollection(Type type) return false; } - public bool TryGetValue(object target, string member, out object o) + public bool TryGetValue(object target, string member, [NotNullWhen(true)] out object? o) { if (!IsStringKeyedGenericDictionary) { @@ -92,8 +93,8 @@ public bool TryGetValue(object target, string member, out object o) // we could throw when indexing with an invalid key try { - var parameters = new[] { member, _valueType.IsValueType ? Activator.CreateInstance(_valueType) : null }; - var result = (bool) _tryGetValueMethod.Invoke(target, parameters); + var parameters = new[] { member, _valueType!.IsValueType ? Activator.CreateInstance(_valueType) : null }; + var result = (bool) _tryGetValueMethod!.Invoke(target, parameters); o = parameters[1]; return result; } @@ -111,7 +112,7 @@ public ICollection GetKeys(object target) ExceptionHelper.ThrowInvalidOperationException("Not a string-keyed dictionary"); } - return (ICollection) _keysAccessor.GetValue(target); + return (ICollection) _keysAccessor!.GetValue(target); } } } diff --git a/Jint/Runtime/Interop/TypeReference.cs b/Jint/Runtime/Interop/TypeReference.cs index bb898ff646..3de318fb09 100644 --- a/Jint/Runtime/Interop/TypeReference.cs +++ b/Jint/Runtime/Interop/TypeReference.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Collections.Concurrent; using System.Reflection; using Jint.Collections; diff --git a/Jint/Runtime/Interop/TypeReferencePrototype.cs b/Jint/Runtime/Interop/TypeReferencePrototype.cs index 5c5ef67e78..252687cbdd 100644 --- a/Jint/Runtime/Interop/TypeReferencePrototype.cs +++ b/Jint/Runtime/Interop/TypeReferencePrototype.cs @@ -1,4 +1,4 @@ -//using Jint.Native; +//using Jint.Native; //using Jint.Native.Object; //namespace Jint.Runtime.Interop @@ -37,4 +37,4 @@ // return typeReference.Type.FullName; // } // } -//} \ No newline at end of file +//} diff --git a/Jint/Runtime/Interop/TypeResolver.cs b/Jint/Runtime/Interop/TypeResolver.cs index f4325574ba..70a7aa72dc 100644 --- a/Jint/Runtime/Interop/TypeResolver.cs +++ b/Jint/Runtime/Interop/TypeResolver.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Reflection; using System.Threading; @@ -44,7 +45,7 @@ private static IEnumerable NameCreator(MemberInfo info) /// public StringComparer MemberNameComparer { get; set; } = DefaultMemberNameComparer.Instance; - internal ReflectionAccessor GetAccessor(Engine engine, Type type, string member, Func accessorFactory = null) + internal ReflectionAccessor GetAccessor(Engine engine, Type type, string member, Func? accessorFactory = null) { var key = new ClrPropertyDescriptorFactoriesKey(type, member); @@ -96,7 +97,7 @@ private ReflectionAccessor ResolvePropertyDescriptorFactory( } // try to find a single explicit property implementation - List list = null; + List? list = null; var typeResolverMemberNameComparer = MemberNameComparer; var typeResolverMemberNameCreator = MemberNameCreator; foreach (var iface in type.GetInterfaces()) @@ -131,7 +132,7 @@ private ReflectionAccessor ResolvePropertyDescriptorFactory( } // try to find explicit method implementations - List explicitMethods = null; + List? explicitMethods = null; foreach (var iface in type.GetInterfaces()) { foreach (var imethod in iface.GetMethods()) @@ -199,11 +200,11 @@ internal bool TryFindMemberAccessor( Type type, string memberName, BindingFlags bindingFlags, - PropertyInfo indexerToTry, - out ReflectionAccessor accessor) + PropertyInfo? indexerToTry, + [NotNullWhen(true)] out ReflectionAccessor? accessor) { // look for a property, bit be wary of indexers, we don't want indexers which have name "Item" to take precedence - PropertyInfo property = null; + PropertyInfo? property = null; var memberNameComparer = MemberNameComparer; var typeResolverMemberNameCreator = MemberNameCreator; foreach (var p in type.GetProperties(bindingFlags)) @@ -235,7 +236,7 @@ internal bool TryFindMemberAccessor( } // look for a field - FieldInfo field = null; + FieldInfo? field = null; foreach (var f in type.GetFields(bindingFlags)) { if (!Filter(engine, f)) @@ -260,7 +261,7 @@ internal bool TryFindMemberAccessor( } // if no properties were found then look for a method - List methods = null; + List? methods = null; foreach (var m in type.GetMethods(bindingFlags)) { if (!Filter(engine, m)) diff --git a/Jint/Runtime/Interpreter/EvaluationContext.cs b/Jint/Runtime/Interpreter/EvaluationContext.cs index 24db6f4557..f47eaea815 100644 --- a/Jint/Runtime/Interpreter/EvaluationContext.cs +++ b/Jint/Runtime/Interpreter/EvaluationContext.cs @@ -19,7 +19,7 @@ public EvaluationContext(Engine engine, in Completion? resumedCompletion = null) public Completion ResumedCompletion { get; } public bool DebugMode { get; } - public Node LastSyntaxNode { get; set; } + public Node LastSyntaxNode { get; set; } = null!; public bool OperatorOverloadingAllowed { get; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/BindingPatternAssignmentExpression.cs b/Jint/Runtime/Interpreter/Expressions/BindingPatternAssignmentExpression.cs index f71763e7b4..1b577467bf 100644 --- a/Jint/Runtime/Interpreter/Expressions/BindingPatternAssignmentExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/BindingPatternAssignmentExpression.cs @@ -11,7 +11,7 @@ namespace Jint.Runtime.Interpreter.Expressions internal sealed class BindingPatternAssignmentExpression : JintExpression { private readonly BindingPattern _pattern; - private JintExpression _right; + private JintExpression _right = null!; public BindingPatternAssignmentExpression(AssignmentExpression expression) : base(expression) { @@ -45,7 +45,7 @@ internal static Completion ProcessPatterns( EvaluationContext context, BindingPattern pattern, JsValue argument, - EnvironmentRecord environment, + EnvironmentRecord? environment, bool checkPatternPropertyReference = true) { if (pattern is ArrayPattern ap) @@ -81,14 +81,14 @@ private static Completion HandleArrayPattern( EvaluationContext context, ArrayPattern pattern, JsValue argument, - EnvironmentRecord environment, + EnvironmentRecord? environment, bool checkReference) { var engine = context.Engine; var realm = engine.Realm; var obj = TypeConverter.ToObject(realm, argument); - ArrayOperations arrayOperations = null; - IteratorInstance iterator = null; + ArrayOperations? arrayOperations = null; + IteratorInstance? iterator = null; // optimize for array unless someone has touched the iterator if (obj.IsArrayLike && obj.HasOriginalIterator) @@ -119,7 +119,7 @@ private static Completion HandleArrayPattern( } else { - if (!ConsumeFromIterator(iterator, out _, out done)) + if (!ConsumeFromIterator(iterator!, out _, out done)) { break; } @@ -137,10 +137,10 @@ private static Completion HandleArrayPattern( } else { - ConsumeFromIterator(iterator, out value, out done); + ConsumeFromIterator(iterator!, out value, out done); } - AssignToIdentifier(engine, identifier.Name, value, environment, checkReference); + AssignToIdentifier(engine, identifier.Name!, value, environment, checkReference); } else if (left is MemberExpression me) { @@ -153,7 +153,7 @@ private static Completion HandleArrayPattern( } else { - ConsumeFromIterator(iterator, out value, out done); + ConsumeFromIterator(iterator!, out value, out done); } AssignToReference(engine, reference, value, environment); @@ -167,7 +167,7 @@ private static Completion HandleArrayPattern( } else { - iterator.TryIteratorStep(out var temp); + iterator!.TryIteratorStep(out var temp); value = temp; } ProcessPatterns(context, bindingPattern, value, environment); @@ -175,7 +175,7 @@ private static Completion HandleArrayPattern( else if (left is RestElement restElement) { close = true; - Reference reference = null; + Reference? reference = null; if (restElement.Argument is MemberExpression memberExpression) { reference = GetReferenceFromMember(context, memberExpression); @@ -199,7 +199,7 @@ private static Completion HandleArrayPattern( done = true; do { - if (!iterator.TryIteratorStep(out var item)) + if (!iterator!.TryIteratorStep(out var item)) { done = true; break; @@ -214,7 +214,7 @@ private static Completion HandleArrayPattern( if (restElement.Argument is Identifier leftIdentifier) { - AssignToIdentifier(engine, leftIdentifier.Name, array, environment, checkReference); + AssignToIdentifier(engine, leftIdentifier.Name!, array, environment, checkReference); } else if (restElement.Argument is BindingPattern bp) { @@ -222,7 +222,7 @@ private static Completion HandleArrayPattern( } else { - AssignToReference(engine, reference, array, environment); + AssignToReference(engine, reference!, array, environment); } } else if (left is AssignmentPattern assignmentPattern) @@ -234,7 +234,7 @@ private static Completion HandleArrayPattern( } else { - ConsumeFromIterator(iterator, out value, out done); + ConsumeFromIterator(iterator!, out value, out done); } if (value.IsUndefined()) @@ -252,10 +252,10 @@ private static Completion HandleArrayPattern( { if (assignmentPattern.Right.IsFunctionDefinition()) { - ((FunctionInstance) value).SetFunctionName(new JsString(leftIdentifier.Name)); + ((FunctionInstance) value).SetFunctionName(new JsString(leftIdentifier.Name!)); } - AssignToIdentifier(engine, leftIdentifier.Name, value, environment, checkReference); + AssignToIdentifier(engine, leftIdentifier.Name!, value, environment, checkReference); } else if (assignmentPattern.Left is BindingPattern bp) { @@ -292,7 +292,7 @@ private static Completion HandleObjectPattern( EvaluationContext context, ObjectPattern pattern, JsValue argument, - EnvironmentRecord environment, + EnvironmentRecord? environment, bool checkReference) { var processedProperties = pattern.Properties.Count > 0 && pattern.Properties[pattern.Properties.Count - 1] is RestElement @@ -346,10 +346,10 @@ private static Completion HandleObjectPattern( if (assignmentPattern.Right.IsFunctionDefinition()) { - ((FunctionInstance) value).SetFunctionName(target.Name); + ((FunctionInstance) value).SetFunctionName(target!.Name); } - AssignToIdentifier(context.Engine, target.Name, value, environment, checkReference); + AssignToIdentifier(context.Engine, target!.Name!, value, environment, checkReference); } else if (p.Value is BindingPattern bindingPattern) { @@ -367,7 +367,7 @@ private static Completion HandleObjectPattern( var identifierReference = p.Value as Identifier; var target = identifierReference ?? identifier; source.TryGetValue(sourceKey, out var v); - AssignToIdentifier(context.Engine, target.Name, v, environment, checkReference); + AssignToIdentifier(context.Engine, target!.Name!, v, environment, checkReference); } } else @@ -375,10 +375,10 @@ private static Completion HandleObjectPattern( var restElement = (RestElement) pattern.Properties[i]; if (restElement.Argument is Identifier leftIdentifier) { - var count = Math.Max(0, source.Properties?.Count ?? 0) - processedProperties.Count; + var count = Math.Max(0, source.Properties?.Count ?? 0) - processedProperties!.Count; var rest = context.Engine.Realm.Intrinsics.Object.Construct(count); source.CopyDataProperties(rest, processedProperties); - AssignToIdentifier(context.Engine, leftIdentifier.Name, rest, environment, checkReference); + AssignToIdentifier(context.Engine, leftIdentifier.Name!, rest, environment, checkReference); } else if (restElement.Argument is BindingPattern bp) { @@ -405,7 +405,7 @@ private static void AssignToReference( Engine engine, Reference lhs, JsValue v, - EnvironmentRecord environment) + EnvironmentRecord? environment) { if (environment is null) { @@ -434,7 +434,7 @@ private static void AssignToIdentifier( Engine engine, string name, JsValue rval, - EnvironmentRecord environment, + EnvironmentRecord? environment, bool checkReference = true) { var lhs = engine.ResolveBinding(name, environment); diff --git a/Jint/Runtime/Interpreter/Expressions/JintArrayExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintArrayExpression.cs index 881f5b29dc..d8855335b4 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintArrayExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintArrayExpression.cs @@ -7,7 +7,7 @@ namespace Jint.Runtime.Interpreter.Expressions { internal sealed class JintArrayExpression : JintExpression { - private JintExpression[] _expressions; + private JintExpression[] _expressions = Array.Empty(); private bool _hasSpreads; public JintArrayExpression(ArrayExpression expression) : base(expression) @@ -64,7 +64,7 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) } else { - var protocol = new ArraySpreadProtocol(engine, a, iterator, arrayIndexCounter); + var protocol = new ArraySpreadProtocol(engine, a, iterator!, arrayIndexCounter); protocol.Execute(); arrayIndexCounter += protocol._addedCount; } @@ -108,4 +108,4 @@ protected override void ProcessItem(JsValue[] args, JsValue currentValue) } } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintArrowFunctionExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintArrowFunctionExpression.cs index ed9f55bf67..37057254a9 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintArrowFunctionExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintArrowFunctionExpression.cs @@ -34,4 +34,4 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) return NormalCompletion(closure); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintAssignmentExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintAssignmentExpression.cs index ff2fe6993e..fe37196ead 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintAssignmentExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintAssignmentExpression.cs @@ -49,7 +49,7 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) if (context.OperatorOverloadingAllowed) { - string operatorClrName = null; + string? operatorClrName = null; switch (_operator) { case AssignmentOperator.PlusAssign: @@ -331,10 +331,10 @@ private JsValue NamedEvaluation(EvaluationContext context, JintExpression expres internal sealed class SimpleAssignmentExpression : JintExpression { - private JintExpression _left; - private JintExpression _right; + private JintExpression _left = null!; + private JintExpression _right = null!; - private JintIdentifierExpression _leftIdentifier; + private JintIdentifierExpression? _leftIdentifier; private bool _evalOrArguments; public SimpleAssignmentExpression(AssignmentExpression expression) : base(expression) diff --git a/Jint/Runtime/Interpreter/Expressions/JintBinaryExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintBinaryExpression.cs index fa7c2668b9..50d52bd4b8 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintBinaryExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintBinaryExpression.cs @@ -1,4 +1,5 @@ using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; using System.Numerics; using System.Reflection; using System.Runtime.CompilerServices; @@ -13,7 +14,7 @@ namespace Jint.Runtime.Interpreter.Expressions { internal abstract class JintBinaryExpression : JintExpression { - private readonly record struct OperatorKey(string OperatorName, Type Left, Type Right); + private readonly record struct OperatorKey(string? OperatorName, Type Left, Type Right); private static readonly ConcurrentDictionary _knownOperators = new(); private readonly JintExpression _left; @@ -31,8 +32,8 @@ internal static bool TryOperatorOverloading( EvaluationContext context, JsValue leftValue, JsValue rightValue, - string clrName, - out object result) + string? clrName, + [NotNullWhen(true)] out object? result) { var left = leftValue.ToObject(); var right = rightValue.ToObject(); @@ -77,7 +78,7 @@ internal static bool TryOperatorOverloading( internal static JintExpression Build(Engine engine, BinaryExpression expression) { - JintBinaryExpression result = null; + JintBinaryExpression? result = null; switch (expression.Operator) { case BinaryOperator.StrictlyEqual: @@ -707,7 +708,7 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) private sealed class BitwiseBinaryExpression : JintBinaryExpression { - private string OperatorClrName + private string? OperatorClrName { get { @@ -755,7 +756,7 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) int leftValue = lnum.AsInteger(); int rightValue = rnum.AsInteger(); - JsValue result = null; + JsValue? result = null; switch (_operator) { case BinaryOperator.BitwiseAnd: diff --git a/Jint/Runtime/Interpreter/Expressions/JintCallExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintCallExpression.cs index 356266ed73..ccdbc5208d 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintCallExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintCallExpression.cs @@ -9,10 +9,10 @@ namespace Jint.Runtime.Interpreter.Expressions { internal sealed class JintCallExpression : JintExpression { - private CachedArgumentsHolder _cachedArguments; + private CachedArgumentsHolder _cachedArguments = null!; private bool _cached; - private JintExpression _calleeExpression; + private JintExpression _calleeExpression = null!; private bool _hasSpreads; public JintCallExpression(CallExpression expression) : base(expression) @@ -30,10 +30,9 @@ protected override void Initialize(EvaluationContext context) JintArguments = new JintExpression[expression.Arguments.Count] }; - static bool CanSpread(Node e) + static bool CanSpread(Node? e) { - return e?.Type == Nodes.SpreadElement - || e is AssignmentExpression ae && ae.Right?.Type == Nodes.SpreadElement; + return e?.Type == Nodes.SpreadElement || e is AssignmentExpression { Right.Type: Nodes.SpreadElement }; } bool cacheable = true; @@ -82,13 +81,13 @@ private JsValue SuperCall(EvaluationContext context) var thisEnvironment = (FunctionEnvironmentRecord) engine.ExecutionContext.GetThisEnvironment(); var newTarget = engine.GetNewTarget(thisEnvironment); var func = GetSuperConstructor(thisEnvironment); - if (!func.IsConstructor) + if (func is null || !func.IsConstructor) { ExceptionHelper.ThrowTypeError(engine.Realm, "Not a constructor"); } var argList = ArgumentListEvaluation(context); - var result = ((IConstructor) func).Construct(argList, newTarget); + var result = ((IConstructor) func).Construct(argList, newTarget ?? JsValue.Undefined); var thisER = (FunctionEnvironmentRecord) engine.ExecutionContext.GetThisEnvironment(); return thisER.BindThisValue(result); } @@ -96,7 +95,7 @@ private JsValue SuperCall(EvaluationContext context) /// /// https://tc39.es/ecma262/#sec-getsuperconstructor /// - private static ObjectInstance GetSuperConstructor(FunctionEnvironmentRecord thisEnvironment) + private static ObjectInstance? GetSuperConstructor(FunctionEnvironmentRecord thisEnvironment) { var envRec = thisEnvironment; var activeFunction = envRec._functionObject; @@ -232,7 +231,7 @@ private static bool IsInTailPosition(CallExpression call) private JsValue[] ArgumentListEvaluation(EvaluationContext context) { var cachedArguments = _cachedArguments; - var arguments = System.Array.Empty(); + var arguments = Array.Empty(); if (_cached) { arguments = cachedArguments.CachedArguments; @@ -258,8 +257,8 @@ private JsValue[] ArgumentListEvaluation(EvaluationContext context) private sealed class CachedArgumentsHolder { - internal JintExpression[] JintArguments; - internal JsValue[] CachedArguments; + internal JintExpression[] JintArguments = Array.Empty(); + internal JsValue[] CachedArguments = Array.Empty(); } } } diff --git a/Jint/Runtime/Interpreter/Expressions/JintClassExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintClassExpression.cs index 4624064ff2..9f1770b640 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintClassExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintClassExpression.cs @@ -18,4 +18,4 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) return _classDefinition.BuildConstructor(context, env); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintConditionalExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintConditionalExpression.cs index 33682d190e..63d265474e 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintConditionalExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintConditionalExpression.cs @@ -22,4 +22,4 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) : _alternate.GetValue(context); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintConstantExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintConstantExpression.cs index 03f15cda43..81e6163ce8 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintConstantExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintConstantExpression.cs @@ -25,4 +25,4 @@ public override Completion GetValue(EvaluationContext context) protected override ExpressionResult EvaluateInternal(EvaluationContext context) => NormalCompletion(_value); } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintExpression.cs index f7d9476c98..23f85733c2 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintExpression.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; @@ -389,7 +387,7 @@ private static JsValue CompareComplex(JsValue x, JsValue y, bool leftFirst) return false; } - var normalized = new BigInteger(System.Math.Ceiling(numberB)); + var normalized = new BigInteger(Math.Ceiling(numberB)); return TypeConverter.ToBigInt(px) < normalized; } @@ -418,7 +416,7 @@ private static JsValue CompareComplex(JsValue x, JsValue y, bool leftFirst) return true; } - var normalizedA = new BigInteger(System.Math.Floor(numberA)); + var normalizedA = new BigInteger(Math.Floor(numberA)); return normalizedA < TypeConverter.ToBigInt(py); } @@ -473,7 +471,7 @@ protected static void BuildArguments(EvaluationContext context, JintExpression[] protected static JsValue[] BuildArgumentsWithSpreads(EvaluationContext context, JintExpression[] jintExpressions) { - var args = new System.Collections.Generic.List(jintExpressions.Length); + var args = new List(jintExpressions.Length); for (var i = 0; i < jintExpressions.Length; i++) { var jintExpression = jintExpressions[i]; @@ -494,7 +492,7 @@ protected static JsValue[] BuildArgumentsWithSpreads(EvaluationContext context, } else { - var protocol = new ArraySpreadProtocol(context.Engine, args, iterator); + var protocol = new ArraySpreadProtocol(context.Engine, args, iterator!); protocol.Execute(); } } @@ -510,11 +508,11 @@ protected static JsValue[] BuildArgumentsWithSpreads(EvaluationContext context, private sealed class ArraySpreadProtocol : IteratorProtocol { - private readonly System.Collections.Generic.List _instance; + private readonly List _instance; public ArraySpreadProtocol( Engine engine, - System.Collections.Generic.List instance, + List instance, IteratorInstance iterator) : base(engine, iterator, 0) { _instance = instance; @@ -532,4 +530,4 @@ protected static bool AreIntegerOperands(JsValue left, JsValue right) return left._type == right._type && left._type == InternalTypes.Integer; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintFunctionExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintFunctionExpression.cs index 7424849169..4235cfc266 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintFunctionExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintFunctionExpression.cs @@ -22,8 +22,8 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) public override Completion GetValue(EvaluationContext context) { var closure = !_function.Function.Generator - ? InstantiateOrdinaryFunctionExpression(context, _function.Name) - : InstantiateGeneratorFunctionExpression(context, _function.Name); + ? InstantiateOrdinaryFunctionExpression(context, _function.Name!) + : InstantiateGeneratorFunctionExpression(context, _function.Name!); return Completion.Normal(closure, _expression.Location); } @@ -31,17 +31,17 @@ public override Completion GetValue(EvaluationContext context) /// /// https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionexpression /// - private ScriptFunctionInstance InstantiateOrdinaryFunctionExpression(EvaluationContext context, string name = "") + private ScriptFunctionInstance InstantiateOrdinaryFunctionExpression(EvaluationContext context, string? name = "") { var engine = context.Engine; var runningExecutionContext = engine.ExecutionContext; var scope = runningExecutionContext.LexicalEnvironment; - DeclarativeEnvironmentRecord funcEnv = null; + DeclarativeEnvironmentRecord? funcEnv = null; if (!string.IsNullOrWhiteSpace(name)) { funcEnv = JintEnvironment.NewDeclarativeEnvironment(engine, engine.ExecutionContext.LexicalEnvironment); - funcEnv.CreateImmutableBinding(name, strict: false); + funcEnv.CreateImmutableBinding(name!, strict: false); } var privateScope = runningExecutionContext.PrivateEnvironment; @@ -65,7 +65,7 @@ private ScriptFunctionInstance InstantiateOrdinaryFunctionExpression(EvaluationC } closure.MakeConstructor(); - funcEnv?.InitializeBinding(name, closure); + funcEnv?.InitializeBinding(name!, closure); return closure; } diff --git a/Jint/Runtime/Interpreter/Expressions/JintIdentifierExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintIdentifierExpression.cs index df97f4f50f..c055f3c295 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintIdentifierExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintIdentifierExpression.cs @@ -8,11 +8,11 @@ namespace Jint.Runtime.Interpreter.Expressions internal sealed class JintIdentifierExpression : JintExpression { internal readonly EnvironmentRecord.BindingName _expressionName; - private readonly JsValue _calculatedValue; + private readonly JsValue? _calculatedValue; public JintIdentifierExpression(Identifier expression) : base(expression) { - _expressionName = new EnvironmentRecord.BindingName(expression.Name); + _expressionName = new EnvironmentRecord.BindingName(expression.Name!); if (expression.Name == "undefined") { _calculatedValue = JsValue.Undefined; @@ -75,4 +75,4 @@ public override Completion GetValue(EvaluationContext context) return Completion.Normal(value, _expression.Location); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintImportExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintImportExpression.cs index 2d36ccf47c..963a17d414 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintImportExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintImportExpression.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima.Ast; using Jint.Native.Promise; diff --git a/Jint/Runtime/Interpreter/Expressions/JintLiteralExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintLiteralExpression.cs index 196e5efef8..60fc0dea25 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintLiteralExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintLiteralExpression.cs @@ -22,7 +22,7 @@ internal static JintExpression Build(Literal expression) return new JintLiteralExpression(expression); } - internal static JsValue ConvertToJsValue(Literal literal) + internal static JsValue? ConvertToJsValue(Literal literal) { if (literal.TokenType == TokenType.BooleanLiteral) { @@ -45,12 +45,12 @@ internal static JsValue ConvertToJsValue(Literal literal) if (literal.TokenType == TokenType.StringLiteral) { - return JsString.Create((string) literal.Value); + return JsString.Create((string) literal.Value!); } if (literal.TokenType == TokenType.BigIntLiteral) { - return JsBigInt.Create((BigInteger) literal.Value); + return JsBigInt.Create((BigInteger) literal.Value!); } return null; @@ -71,7 +71,7 @@ private JsValue ResolveValue(EvaluationContext context) var expression = (Literal) _expression; if (expression.TokenType == TokenType.RegularExpression) { - return context.Engine.Realm.Intrinsics.RegExp.Construct((System.Text.RegularExpressions.Regex) expression.Value, expression.Regex.Pattern, expression.Regex.Flags); + return context.Engine.Realm.Intrinsics.RegExp.Construct((System.Text.RegularExpressions.Regex) expression.Value!, expression.Regex!.Pattern, expression.Regex.Flags); } return JsValue.FromObject(context.Engine, expression.Value); diff --git a/Jint/Runtime/Interpreter/Expressions/JintLogicalAndExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintLogicalAndExpression.cs index a3e90aaaf4..24a5e019f5 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintLogicalAndExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintLogicalAndExpression.cs @@ -5,8 +5,8 @@ namespace Jint.Runtime.Interpreter.Expressions { internal sealed class JintLogicalAndExpression : JintExpression { - private JintExpression _left; - private JintExpression _right; + private JintExpression _left = null!; + private JintExpression _right = null!; public JintLogicalAndExpression(BinaryExpression expression) : base(expression) { @@ -37,4 +37,4 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) return _right.GetValue(context); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintLogicalOrExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintLogicalOrExpression.cs index 9ac7eceff8..a965ffdd14 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintLogicalOrExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintLogicalOrExpression.cs @@ -31,4 +31,4 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) return _right.GetValue(context); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintMemberExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintMemberExpression.cs index 500bf22db1..0b1c554481 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintMemberExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintMemberExpression.cs @@ -10,19 +10,19 @@ namespace Jint.Runtime.Interpreter.Expressions /// internal sealed class JintMemberExpression : JintExpression { - private MemberExpression _memberExpression; - private JintExpression _objectExpression; - private JintExpression _propertyExpression; - private JsValue _determinedProperty; + private readonly MemberExpression _memberExpression; + private JintExpression _objectExpression = null!; + private JintExpression? _propertyExpression; + private JsValue? _determinedProperty; public JintMemberExpression(MemberExpression expression) : base(expression) { _initialized = false; + _memberExpression = (MemberExpression) _expression; } protected override void Initialize(EvaluationContext context) { - _memberExpression = (MemberExpression) _expression; _objectExpression = Build(context.Engine, _memberExpression.Object); if (!_memberExpression.Computed) @@ -42,9 +42,9 @@ protected override void Initialize(EvaluationContext context) protected override ExpressionResult EvaluateInternal(EvaluationContext context) { - JsValue actualThis = null; - string baseReferenceName = null; - JsValue baseValue = null; + JsValue? actualThis = null; + string? baseReferenceName = null; + JsValue? baseValue = null; var isStrictModeCode = StrictModeScope.IsStrictModeCode; var engine = context.Engine; @@ -96,7 +96,7 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) return NormalCompletion(Undefined.Instance); } - var property = _determinedProperty ?? _propertyExpression.GetValue(context).Value; + var property = _determinedProperty ?? _propertyExpression!.GetValue(context).Value; if (baseValue.IsNullOrUndefined()) { // we can use base data types securely, object evaluation can mess things up @@ -104,7 +104,7 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) ? TypeConverter.ToString(property) : _determinedProperty?.ToString() ?? baseReferenceName; - TypeConverter.CheckObjectCoercible(engine, baseValue, _memberExpression.Property, referenceName); + TypeConverter.CheckObjectCoercible(engine, baseValue, _memberExpression.Property, referenceName!); } // only convert if necessary @@ -119,4 +119,4 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) _expression.Location); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintNewExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintNewExpression.cs index 7bd3db23cb..3d75566c62 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintNewExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintNewExpression.cs @@ -5,7 +5,7 @@ namespace Jint.Runtime.Interpreter.Expressions { internal sealed class JintNewExpression : JintExpression { - private JintExpression _calleeExpression; + private JintExpression _calleeExpression = null!; private JintExpression[] _jintArguments = Array.Empty(); private bool _hasSpreads; diff --git a/Jint/Runtime/Interpreter/Expressions/JintObjectExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintObjectExpression.cs index 3125d14740..d9591b44b0 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintObjectExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintObjectExpression.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima.Ast; using Jint.Collections; using Jint.Native; @@ -14,8 +12,8 @@ namespace Jint.Runtime.Interpreter.Expressions /// internal sealed class JintObjectExpression : JintExpression { - private JintExpression[] _valueExpressions = System.Array.Empty(); - private ObjectProperty?[] _properties = System.Array.Empty(); + private JintExpression[] _valueExpressions = Array.Empty(); + private ObjectProperty?[] _properties = Array.Empty(); // check if we can do a shortcut when all are object properties // and don't require duplicate checking @@ -142,7 +140,7 @@ private ExpressionResult BuildObjectFast(EvaluationContext context) var objectProperty = _properties[i]; var valueExpression = _valueExpressions[i]; var propValue = valueExpression.GetValue(context).Value!.Clone(); - properties[objectProperty!._key] = new PropertyDescriptor(propValue, PropertyFlag.ConfigurableEnumerableWritable); + properties[objectProperty!._key!] = new PropertyDescriptor(propValue, PropertyFlag.ConfigurableEnumerableWritable); } obj.SetProperties(properties); @@ -219,7 +217,7 @@ private ExpressionResult BuildObjectNormal(EvaluationContext context) continue; } } - + var propDesc = new PropertyDescriptor(propValue, PropertyFlag.ConfigurableEnumerableWritable); obj.DefinePropertyOrThrow(propName, propDesc); } diff --git a/Jint/Runtime/Interpreter/Expressions/JintSequenceExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintSequenceExpression.cs index 2335708ec0..8a179e1592 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintSequenceExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintSequenceExpression.cs @@ -5,7 +5,7 @@ namespace Jint.Runtime.Interpreter.Expressions { internal sealed class JintSequenceExpression : JintExpression { - private JintExpression[] _expressions; + private JintExpression[] _expressions = Array.Empty(); public JintSequenceExpression(SequenceExpression expression) : base(expression) { @@ -37,4 +37,4 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) return NormalCompletion(result); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintSpreadExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintSpreadExpression.cs index 0368cc9378..74df0f9818 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintSpreadExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintSpreadExpression.cs @@ -7,7 +7,7 @@ namespace Jint.Runtime.Interpreter.Expressions internal sealed class JintSpreadExpression : JintExpression { private readonly JintExpression _argument; - private readonly string _argumentName; + private readonly string? _argumentName; public JintSpreadExpression(Engine engine, SpreadElement expression) : base(expression) { @@ -30,7 +30,7 @@ public override Completion GetValue(EvaluationContext context) return Completion.Normal(objectInstance, _expression.Location); } - internal void GetValueAndCheckIterator(EvaluationContext context, out JsValue instance, out IteratorInstance iterator) + internal void GetValueAndCheckIterator(EvaluationContext context, out JsValue instance, out IteratorInstance? iterator) { instance = _argument.GetValue(context).Value; if (instance is null || !instance.TryGetIterator(context.Engine.Realm, out iterator)) @@ -40,4 +40,4 @@ internal void GetValueAndCheckIterator(EvaluationContext context, out JsValue in } } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintSuperExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintSuperExpression.cs index 8019d99e62..96114dad0d 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintSuperExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintSuperExpression.cs @@ -14,7 +14,7 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) var envRec = (FunctionEnvironmentRecord) context.Engine.ExecutionContext.GetThisEnvironment(); var activeFunction = envRec._functionObject; var superConstructor = activeFunction.GetPrototypeOf(); - return NormalCompletion(superConstructor); + return NormalCompletion(superConstructor!); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintTaggedTemplateExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintTaggedTemplateExpression.cs index c6e126ae75..c7e6409ce2 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintTaggedTemplateExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintTaggedTemplateExpression.cs @@ -10,8 +10,8 @@ internal sealed class JintTaggedTemplateExpression : JintExpression internal static readonly JsString PropertyRaw = new JsString("raw"); private readonly TaggedTemplateExpression _taggedTemplateExpression; - private JintExpression _tagIdentifier; - private JintTemplateLiteralExpression _quasi; + private JintExpression _tagIdentifier = null!; + private JintTemplateLiteralExpression _quasi = null!; public JintTaggedTemplateExpression(TaggedTemplateExpression expression) : base(expression) { @@ -73,4 +73,4 @@ private ArrayInstance GetTemplateObject(EvaluationContext context) return template; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintTemplateLiteralExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintTemplateLiteralExpression.cs index 9a9575e387..aa0067d44e 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintTemplateLiteralExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintTemplateLiteralExpression.cs @@ -7,7 +7,7 @@ namespace Jint.Runtime.Interpreter.Expressions internal sealed class JintTemplateLiteralExpression : JintExpression { internal readonly TemplateLiteral _templateLiteralExpression; - internal JintExpression[] _expressions; + internal JintExpression[] _expressions = Array.Empty(); public JintTemplateLiteralExpression(TemplateLiteral expression) : base(expression) { @@ -55,4 +55,4 @@ protected override ExpressionResult EvaluateInternal(EvaluationContext context) return NormalCompletion(BuildString(context)); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintThisExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintThisExpression.cs index 2219d73380..d742ac981e 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintThisExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintThisExpression.cs @@ -21,4 +21,4 @@ public override Completion GetValue(EvaluationContext context) return Completion.Normal(context.Engine.ResolveThisBinding(), _expression.Location); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintUnaryExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintUnaryExpression.cs index 9abcfee61e..73cd1bfaf5 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintUnaryExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintUnaryExpression.cs @@ -5,6 +5,7 @@ using Jint.Runtime.Interop; using Jint.Runtime.References; using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; using System.Numerics; using System.Reflection; @@ -13,7 +14,7 @@ namespace Jint.Runtime.Interpreter.Expressions internal sealed class JintUnaryExpression : JintExpression { private readonly record struct OperatorKey(string OperatorName, Type Operand); - private static readonly ConcurrentDictionary _knownOperators = new(); + private static readonly ConcurrentDictionary _knownOperators = new(); private readonly JintExpression _argument; private readonly UnaryOperator _operator; @@ -159,7 +160,7 @@ private JsValue EvaluateJsValue(EvaluationContext context) ExceptionHelper.ThrowSyntaxError(engine.Realm); } - var bindings = r.GetBase().TryCast(); + var bindings = (EnvironmentRecord) r.GetBase(); var property = referencedName; engine._referencePool.Return(r); @@ -243,7 +244,7 @@ private static JsValue EvaluateMinus(JsValue value) return JsBigInt.Create(BigInteger.Negate(bigInt)); } - internal static bool TryOperatorOverloading(EvaluationContext context, JsValue value, string clrName, out JsValue result) + internal static bool TryOperatorOverloading(EvaluationContext context, JsValue value, string clrName, [NotNullWhen(true)] out JsValue? result) { var operand = value.ToObject(); @@ -255,7 +256,7 @@ internal static bool TryOperatorOverloading(EvaluationContext context, JsValue v var key = new OperatorKey(clrName, operandType); var method = _knownOperators.GetOrAdd(key, _ => { - MethodInfo foundMethod = null; + MethodInfo? foundMethod = null; foreach (var x in operandType.GetOperatorOverloadMethods()) { if (x.Name == clrName && x.GetParameters().Length == 1) diff --git a/Jint/Runtime/Interpreter/Expressions/JintUpdateExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintUpdateExpression.cs index 020deb8203..6d40e5c0cc 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintUpdateExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintUpdateExpression.cs @@ -7,11 +7,11 @@ namespace Jint.Runtime.Interpreter.Expressions { internal sealed class JintUpdateExpression : JintExpression { - private JintExpression _argument; + private JintExpression _argument = null!; private int _change; private bool _prefix; - private JintIdentifierExpression _leftIdentifier; + private JintIdentifierExpression? _leftIdentifier; private bool _evalOrArguments; public JintUpdateExpression(UpdateExpression expression) : base(expression) @@ -64,7 +64,7 @@ private JsValue UpdateNonIdentifier(EvaluationContext context) var value = engine.GetValue(reference, false); var isInteger = value._type == InternalTypes.Integer; - JsValue newValue = null; + JsValue? newValue = null; var operatorOverloaded = false; if (context.OperatorOverloadingAllowed) @@ -92,12 +92,12 @@ private JsValue UpdateNonIdentifier(EvaluationContext context) } } - engine.PutValue(reference, newValue); + engine.PutValue(reference, newValue!); engine._referencePool.Return(reference); if (_prefix) { - return newValue; + return newValue!; } else { @@ -115,10 +115,10 @@ private JsValue UpdateNonIdentifier(EvaluationContext context) } } - private JsValue UpdateIdentifier(EvaluationContext context) + private JsValue? UpdateIdentifier(EvaluationContext context) { var strict = StrictModeScope.IsStrictModeCode; - var name = _leftIdentifier._expressionName; + var name = _leftIdentifier!._expressionName; var engine = context.Engine; var env = engine.ExecutionContext.LexicalEnvironment; if (JintEnvironment.TryGetIdentifierEnvironmentWithBindingValue( @@ -135,7 +135,7 @@ private JsValue UpdateIdentifier(EvaluationContext context) var isInteger = value._type == InternalTypes.Integer; - JsValue newValue = null; + JsValue? newValue = null; var operatorOverloaded = false; if (context.OperatorOverloadingAllowed) @@ -163,7 +163,7 @@ private JsValue UpdateIdentifier(EvaluationContext context) } } - environmentRecord.SetMutableBinding(name.Key.Name, newValue, strict); + environmentRecord.SetMutableBinding(name.Key.Name, newValue!, strict); if (_prefix) { return newValue; @@ -180,4 +180,4 @@ private JsValue UpdateIdentifier(EvaluationContext context) return null; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Expressions/NullishCoalescingExpression.cs b/Jint/Runtime/Interpreter/Expressions/NullishCoalescingExpression.cs index bc699c8346..3fdb8cd528 100644 --- a/Jint/Runtime/Interpreter/Expressions/NullishCoalescingExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/NullishCoalescingExpression.cs @@ -7,8 +7,8 @@ namespace Jint.Runtime.Interpreter.Expressions internal sealed class NullishCoalescingExpression : JintExpression { private readonly JintExpression _left; - private readonly JintExpression _right; - private readonly JsValue _constant; + private readonly JintExpression? _right; + private readonly JsValue? _constant; public NullishCoalescingExpression(Engine engine, BinaryExpression expression) : base(expression) { @@ -44,7 +44,7 @@ private JsValue EvaluateConstantOrExpression(EvaluationContext context) return !left.IsNullOrUndefined() ? left - : _constant ?? _right.GetValue(context).Value; + : _constant ?? _right!.GetValue(context).Value; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/JintFunctionDefinition.cs b/Jint/Runtime/Interpreter/JintFunctionDefinition.cs index a73a0e0678..90a615eed5 100644 --- a/Jint/Runtime/Interpreter/JintFunctionDefinition.cs +++ b/Jint/Runtime/Interpreter/JintFunctionDefinition.cs @@ -12,14 +12,14 @@ internal sealed class JintFunctionDefinition { private readonly Engine _engine; - private JintExpression _bodyExpression; - private JintStatementList _bodyStatementList; + private JintExpression? _bodyExpression; + private JintStatementList? _bodyStatementList; - public readonly string Name; + public readonly string? Name; public readonly bool Strict; public readonly IFunction Function; - private State _state; + private State? _state; public JintFunctionDefinition( Engine engine, @@ -27,7 +27,7 @@ public JintFunctionDefinition( { _engine = engine; Function = function; - Name = !string.IsNullOrEmpty(function.Id?.Name) ? function.Id.Name : null; + Name = !string.IsNullOrEmpty(function.Id?.Name) ? function.Id!.Name : null; Strict = function.Strict; } @@ -100,22 +100,22 @@ internal sealed class State { public bool HasRestParameter; public int Length; - public Key[] ParameterNames; + public Key[] ParameterNames = null!; public bool HasDuplicates; public bool IsSimpleParameterList; public bool HasParameterExpressions; public bool ArgumentsObjectNeeded; - public List VarNames; - public LinkedList FunctionsToInitialize; + public List? VarNames; + public LinkedList? FunctionsToInitialize; public readonly HashSet FunctionNames = new(); public LexicalVariableDeclaration[] LexicalDeclarations = Array.Empty(); - public HashSet ParameterBindings; - public List VarsToInitialize; + public HashSet? ParameterBindings; + public List? VarsToInitialize; internal struct VariableValuePair { public Key Name; - public JsValue InitialValue; + public JsValue? InitialValue; } internal struct LexicalVariableDeclaration @@ -136,7 +136,7 @@ private State DoInitialize(FunctionInstance functionInstance) var lexicalNames = hoistingScope._lexicalNames; state.VarNames = hoistingScope._varNames; - LinkedList functionsToInitialize = null; + LinkedList? functionsToInitialize = null; if (functionDeclarations != null) { @@ -144,7 +144,7 @@ private State DoInitialize(FunctionInstance functionInstance) for (var i = functionDeclarations.Count - 1; i >= 0; i--) { var d = functionDeclarations[i]; - var fn = d.Id.Name; + var fn = d.Id!.Name!; if (state.FunctionNames.Add(fn)) { functionsToInitialize.AddFirst(new JintFunctionDefinition(_engine, d)); @@ -211,9 +211,9 @@ private State DoInitialize(FunctionInstance functionInstance) for (var i = 0; i < state.VarNames?.Count; i++) { var n = state.VarNames[i]; - if (instantiatedVarNames.Add(n)) + if (instantiatedVarNames!.Add(n)) { - JsValue initialValue = null; + JsValue? initialValue = null; if (!state.ParameterBindings.Contains(n) || state.FunctionNames.Contains(n)) { initialValue = JsValue.Undefined; @@ -253,7 +253,7 @@ private State DoInitialize(FunctionInstance functionInstance) } private static void GetBoundNames( - Expression parameter, + Node? parameter, List target, bool checkDuplicates, ref bool _hasRestParameter, @@ -263,8 +263,8 @@ private static void GetBoundNames( { if (parameter is Identifier identifier) { - _hasDuplicates |= checkDuplicates && target.Contains(identifier.Name); - target.Add(identifier.Name); + _hasDuplicates |= checkDuplicates && target.Contains(identifier.Name!); + target.Add(identifier.Name!); hasArguments |= identifier.Name == "arguments"; return; } @@ -350,9 +350,9 @@ private static void ProcessParameters( var parameter = functionDeclarationParams[i]; if (parameter is Identifier id) { - state.HasDuplicates |= parameterNames.Contains(id.Name); + state.HasDuplicates |= parameterNames.Contains(id.Name!); hasArguments = id.Name == "arguments"; - parameterNames.Add(id.Name); + parameterNames.Add(id.Name!); if (state.IsSimpleParameterList) { state.Length++; diff --git a/Jint/Runtime/Interpreter/JintStatementList.cs b/Jint/Runtime/Interpreter/JintStatementList.cs index 5de1f60441..7f2a4a80a6 100644 --- a/Jint/Runtime/Interpreter/JintStatementList.cs +++ b/Jint/Runtime/Interpreter/JintStatementList.cs @@ -1,4 +1,4 @@ -using Esprima.Ast; +using Esprima.Ast; using Jint.Native; using Jint.Runtime.Environments; using Jint.Runtime.Interpreter.Statements; @@ -9,14 +9,14 @@ internal sealed class JintStatementList { private sealed class Pair { - internal JintStatement Statement; + internal JintStatement Statement = null!; internal Completion? Value; } - private readonly Statement _statement; + private readonly Statement? _statement; private readonly NodeList _statements; - private Pair[] _jintStatements; + private Pair[]? _jintStatements; private bool _initialized; private uint _index; private readonly bool _generator; @@ -37,7 +37,7 @@ public JintStatementList(Program program) { } - public JintStatementList(Statement statement, in NodeList statements) + public JintStatementList(Statement? statement, in NodeList statements) { _statement = statement; _statements = statements; @@ -77,15 +77,15 @@ public Completion Execute(EvaluationContext context) engine.RunBeforeExecuteStatementChecks(_statement); } - JintStatement s = null; - var c = new Completion(CompletionType.Normal, null, null, context.LastSyntaxNode?.Location ?? default); + JintStatement? s = null; + var c = new Completion(CompletionType.Normal, null!, null, context.LastSyntaxNode?.Location ?? default); Completion sl = c; // The value of a StatementList is the value of the last value-producing item in the StatementList - JsValue lastValue = null; + JsValue? lastValue = null; try { - foreach (var pair in _jintStatements) + foreach (var pair in _jintStatements!) { s = pair.Statement; c = pair.Value ?? s.Execute(context); @@ -104,7 +104,7 @@ public Completion Execute(EvaluationContext context) } catch (JavaScriptException v) { - var location = v.Location == default ? s.Location : v.Location; + var location = v.Location == default ? s!.Location : v.Location; var completion = new Completion(CompletionType.Throw, v.Error, null, location); return completion; } @@ -114,7 +114,7 @@ public Completion Execute(EvaluationContext context) { e.Message }); - return new Completion(CompletionType.Throw, error, null, s.Location); + return new Completion(CompletionType.Throw, error, null, s!.Location); } catch (RangeErrorException e) { @@ -122,7 +122,7 @@ public Completion Execute(EvaluationContext context) { e.Message }); - c = new Completion(CompletionType.Throw, error, null, s.Location); + c = new Completion(CompletionType.Throw, error, null, s!.Location); } return new Completion(c.Type, lastValue ?? JsValue.Undefined, c.Target, c.Location); } @@ -158,7 +158,7 @@ internal static void BlockDeclarationInstantiation( if (d is FunctionDeclaration functionDeclaration) { var definition = new JintFunctionDefinition(engine, functionDeclaration); - var fn = definition.Name; + var fn = definition.Name!; var fo = env._engine.Realm.Intrinsics.Function.InstantiateFunctionObject(definition, env, privateEnv); env.InitializeBinding(fn, fo); } diff --git a/Jint/Runtime/Interpreter/Statements/JintBlockStatement.cs b/Jint/Runtime/Interpreter/Statements/JintBlockStatement.cs index 33ea511376..f4e24de45c 100644 --- a/Jint/Runtime/Interpreter/Statements/JintBlockStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintBlockStatement.cs @@ -5,8 +5,8 @@ namespace Jint.Runtime.Interpreter.Statements { internal sealed class JintBlockStatement : JintStatement { - private JintStatementList _statementList; - private List _lexicalDeclarations; + private JintStatementList _statementList = null!; + private List? _lexicalDeclarations; public JintBlockStatement(BlockStatement blockStatement) : base(blockStatement) { @@ -22,7 +22,7 @@ protected override void Initialize(EvaluationContext context) protected override Completion ExecuteInternal(EvaluationContext context) { - EnvironmentRecord oldEnv = null; + EnvironmentRecord? oldEnv = null; var engine = context.Engine; if (_lexicalDeclarations != null) { diff --git a/Jint/Runtime/Interpreter/Statements/JintBreakStatement.cs b/Jint/Runtime/Interpreter/Statements/JintBreakStatement.cs index 8f90f670c4..e575d58389 100644 --- a/Jint/Runtime/Interpreter/Statements/JintBreakStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintBreakStatement.cs @@ -7,7 +7,7 @@ namespace Jint.Runtime.Interpreter.Statements /// internal sealed class JintBreakStatement : JintStatement { - private readonly string _label; + private readonly string? _label; public JintBreakStatement(BreakStatement statement) : base(statement) { @@ -16,7 +16,7 @@ public JintBreakStatement(BreakStatement statement) : base(statement) protected override Completion ExecuteInternal(EvaluationContext context) { - return new Completion(CompletionType.Break, null, _label, Location); + return new Completion(CompletionType.Break, null!, _label, Location); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintClassDeclarationStatement.cs b/Jint/Runtime/Interpreter/Statements/JintClassDeclarationStatement.cs index 497b05e68b..003eb6a764 100644 --- a/Jint/Runtime/Interpreter/Statements/JintClassDeclarationStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintClassDeclarationStatement.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima.Ast; using Jint.Native.Function; diff --git a/Jint/Runtime/Interpreter/Statements/JintContinueStatement.cs b/Jint/Runtime/Interpreter/Statements/JintContinueStatement.cs index b0179d164c..1b979a33f4 100644 --- a/Jint/Runtime/Interpreter/Statements/JintContinueStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintContinueStatement.cs @@ -7,7 +7,7 @@ namespace Jint.Runtime.Interpreter.Statements /// internal sealed class JintContinueStatement : JintStatement { - private readonly string _labelName; + private readonly string? _labelName; public JintContinueStatement(ContinueStatement statement) : base(statement) { @@ -16,7 +16,7 @@ public JintContinueStatement(ContinueStatement statement) : base(statement) protected override Completion ExecuteInternal(EvaluationContext context) { - return new Completion(CompletionType.Continue, _labelName, Location); + return new Completion(CompletionType.Continue, _labelName!, Location); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintDebuggerStatement.cs b/Jint/Runtime/Interpreter/Statements/JintDebuggerStatement.cs index 5c56060342..42b584b4a8 100644 --- a/Jint/Runtime/Interpreter/Statements/JintDebuggerStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintDebuggerStatement.cs @@ -29,7 +29,7 @@ protected override Completion ExecuteInternal(EvaluationContext context) break; } - return new Completion(CompletionType.Normal, null, null, Location); + return new Completion(CompletionType.Normal, null!, null, Location); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintDoWhileStatement.cs b/Jint/Runtime/Interpreter/Statements/JintDoWhileStatement.cs index dd464d8ce4..d9c3260491 100644 --- a/Jint/Runtime/Interpreter/Statements/JintDoWhileStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintDoWhileStatement.cs @@ -9,9 +9,9 @@ namespace Jint.Runtime.Interpreter.Statements /// internal sealed class JintDoWhileStatement : JintStatement { - private JintStatement _body; - private string _labelSetName; - private JintExpression _test; + private JintStatement _body = null!; + private string? _labelSetName; + private JintExpression _test = null!; public JintDoWhileStatement(DoWhileStatement statement) : base(statement) { diff --git a/Jint/Runtime/Interpreter/Statements/JintEmptyStatement.cs b/Jint/Runtime/Interpreter/Statements/JintEmptyStatement.cs index d6beea3943..5c7022597b 100644 --- a/Jint/Runtime/Interpreter/Statements/JintEmptyStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintEmptyStatement.cs @@ -10,7 +10,7 @@ public JintEmptyStatement(EmptyStatement statement) : base(statement) protected override Completion ExecuteInternal(EvaluationContext context) { - return new Completion(CompletionType.Normal, null, null, Location); + return new Completion(CompletionType.Normal, null!, null, Location); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintExportAllDeclaration.cs b/Jint/Runtime/Interpreter/Statements/JintExportAllDeclaration.cs index 6bbbdc7dd4..4be77341ee 100644 --- a/Jint/Runtime/Interpreter/Statements/JintExportAllDeclaration.cs +++ b/Jint/Runtime/Interpreter/Statements/JintExportAllDeclaration.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima.Ast; namespace Jint.Runtime.Interpreter.Statements; diff --git a/Jint/Runtime/Interpreter/Statements/JintExportDefaultDeclaration.cs b/Jint/Runtime/Interpreter/Statements/JintExportDefaultDeclaration.cs index 45cd60695e..2ca19c91f6 100644 --- a/Jint/Runtime/Interpreter/Statements/JintExportDefaultDeclaration.cs +++ b/Jint/Runtime/Interpreter/Statements/JintExportDefaultDeclaration.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima.Ast; using Jint.Native; using Jint.Native.Function; diff --git a/Jint/Runtime/Interpreter/Statements/JintExportNamedDeclaration.cs b/Jint/Runtime/Interpreter/Statements/JintExportNamedDeclaration.cs index 7d89d2e0a5..95d97ad7fd 100644 --- a/Jint/Runtime/Interpreter/Statements/JintExportNamedDeclaration.cs +++ b/Jint/Runtime/Interpreter/Statements/JintExportNamedDeclaration.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima.Ast; using Jint.Native; using Jint.Runtime.Interpreter.Expressions; diff --git a/Jint/Runtime/Interpreter/Statements/JintExpressionStatement.cs b/Jint/Runtime/Interpreter/Statements/JintExpressionStatement.cs index 561630c5f2..8f5d35ebaa 100644 --- a/Jint/Runtime/Interpreter/Statements/JintExpressionStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintExpressionStatement.cs @@ -6,7 +6,7 @@ namespace Jint.Runtime.Interpreter.Statements { internal sealed class JintExpressionStatement : JintStatement { - private JintExpression _expression; + private JintExpression _expression = null!; public JintExpressionStatement(ExpressionStatement statement) : base(statement) { @@ -29,4 +29,4 @@ protected override Completion ExecuteInternal(EvaluationContext context) return new Completion(CompletionType.Normal, context.Engine.GetValue((Reference) result.Value, true), null, Location); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintForInForOfStatement.cs b/Jint/Runtime/Interpreter/Statements/JintForInForOfStatement.cs index 4591bdcbfe..b3a3879d47 100644 --- a/Jint/Runtime/Interpreter/Statements/JintForInForOfStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintForInForOfStatement.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using Esprima.Ast; using Jint.Native; using Jint.Native.Iterator; @@ -19,11 +20,11 @@ internal sealed class JintForInForOfStatement : JintStatement private readonly Expression _rightExpression; private readonly IterationKind _iterationKind; - private JintStatement _body; - private JintExpression _expr; - private BindingPattern _assignmentPattern; - private JintExpression _right; - private List _tdzNames; + private JintStatement _body = null!; + private JintExpression? _expr; + private BindingPattern? _assignmentPattern; + private JintExpression _right = null!; + private List? _tdzNames; private bool _destructuring; private LhsKind _lhsKind; @@ -103,7 +104,7 @@ protected override Completion ExecuteInternal(EvaluationContext context) /// /// https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofheadevaluation-tdznames-expr-iterationkind /// - private bool HeadEvaluation(EvaluationContext context, out IteratorInstance result) + private bool HeadEvaluation(EvaluationContext context, [NotNullWhen(true)] out IteratorInstance? result) { var engine = context.Engine; var oldEnv = engine.ExecutionContext.LexicalEnvironment; @@ -145,7 +146,7 @@ private bool HeadEvaluation(EvaluationContext context, out IteratorInstance resu /// private Completion BodyEvaluation( EvaluationContext context, - JintExpression lhs, + JintExpression? lhs, JintStatement stmt, IteratorInstance iteratorRecord, IterationKind iterationKind, @@ -156,7 +157,7 @@ private Completion BodyEvaluation( var oldEnv = engine.ExecutionContext.LexicalEnvironment; var v = Undefined.Instance; var destructuring = _destructuring; - string lhsName = null; + string? lhsName = null; var completionType = CompletionType.Normal; var close = false; @@ -165,7 +166,7 @@ private Completion BodyEvaluation( { while (true) { - EnvironmentRecord iterationEnv = null; + EnvironmentRecord? iterationEnv = null; if (!iteratorRecord.TryIteratorStep(out var nextResult)) { close = true; @@ -186,7 +187,7 @@ private Completion BodyEvaluation( { if (!destructuring) { - lhsRef = lhs.Evaluate(context); + lhsRef = lhs!.Evaluate(context); } } else @@ -201,7 +202,7 @@ private Completion BodyEvaluation( if (!destructuring) { var identifier = (Identifier) ((VariableDeclaration) _leftNode).Declarations[0].Id; - lhsName ??= identifier.Name; + lhsName ??= identifier.Name!; lhsRef = new ExpressionResult(ExpressionCompletionType.Normal, engine.ResolveBinding(lhsName), identifier.Location); } } @@ -221,18 +222,18 @@ private Completion BodyEvaluation( } else if (lhsKind == LhsKind.LexicalBinding) { - ((Reference) lhsRef.Value).InitializeReferencedBinding(nextValue); + ((Reference) lhsRef.Value!).InitializeReferencedBinding(nextValue); } else { - engine.PutValue((Reference) lhsRef.Value, nextValue); + engine.PutValue((Reference) lhsRef.Value!, nextValue); } } else { status = BindingPatternAssignmentExpression.ProcessPatterns( context, - _assignmentPattern, + _assignmentPattern!, nextValue, iterationEnv, checkPatternPropertyReference: _lhsKind != LhsKind.VarBinding); diff --git a/Jint/Runtime/Interpreter/Statements/JintForStatement.cs b/Jint/Runtime/Interpreter/Statements/JintForStatement.cs index dad44637ac..a00eb74a3b 100644 --- a/Jint/Runtime/Interpreter/Statements/JintForStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintForStatement.cs @@ -10,14 +10,14 @@ namespace Jint.Runtime.Interpreter.Statements /// internal sealed class JintForStatement : JintStatement { - private JintVariableDeclaration _initStatement; - private JintExpression _initExpression; + private JintVariableDeclaration? _initStatement; + private JintExpression? _initExpression; - private JintExpression _test; - private JintExpression _increment; + private JintExpression? _test; + private JintExpression? _increment; - private JintStatement _body; - private List _boundNames; + private JintStatement _body = null!; + private List? _boundNames; private bool _shouldCreatePerIterationEnvironment; @@ -62,15 +62,15 @@ protected override void Initialize(EvaluationContext context) protected override Completion ExecuteInternal(EvaluationContext context) { - EnvironmentRecord oldEnv = null; - EnvironmentRecord loopEnv = null; + EnvironmentRecord? oldEnv = null; + EnvironmentRecord? loopEnv = null; var engine = context.Engine; if (_boundNames != null) { oldEnv = engine.ExecutionContext.LexicalEnvironment; loopEnv = JintEnvironment.NewDeclarativeEnvironment(engine, oldEnv); var loopEnvRec = loopEnv; - var kind = _initStatement._statement.Kind; + var kind = _initStatement!._statement.Kind; for (var i = 0; i < _boundNames.Count; i++) { var name = _boundNames[i]; @@ -144,7 +144,7 @@ private Completion ForBodyEvaluation(EvaluationContext context) if (result.Type == CompletionType.Break && (result.Target == null || result.Target == _statement?.LabelSet?.Name)) { - return NormalCompletion(result.Value); + return NormalCompletion(result.Value!); } if (result.Type != CompletionType.Continue || (result.Target != null && result.Target != _statement?.LabelSet?.Name)) diff --git a/Jint/Runtime/Interpreter/Statements/JintFunctionDeclarationStatement.cs b/Jint/Runtime/Interpreter/Statements/JintFunctionDeclarationStatement.cs index a54175f9a0..244361b4a8 100644 --- a/Jint/Runtime/Interpreter/Statements/JintFunctionDeclarationStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintFunctionDeclarationStatement.cs @@ -14,4 +14,4 @@ protected override Completion ExecuteInternal(EvaluationContext context) return NormalCompletion(JsValue.Undefined); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintIfStatement.cs b/Jint/Runtime/Interpreter/Statements/JintIfStatement.cs index 2835f9a593..893f1b5870 100644 --- a/Jint/Runtime/Interpreter/Statements/JintIfStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintIfStatement.cs @@ -5,9 +5,9 @@ namespace Jint.Runtime.Interpreter.Statements { internal sealed class JintIfStatement : JintStatement { - private JintStatement _statementConsequent; - private JintExpression _test; - private JintStatement _alternate; + private JintStatement _statementConsequent = null!; + private JintExpression _test = null!; + private JintStatement? _alternate; public JintIfStatement(IfStatement statement) : base(statement) { @@ -33,10 +33,10 @@ protected override Completion ExecuteInternal(EvaluationContext context) } else { - return new Completion(CompletionType.Normal, null, Location); + return new Completion(CompletionType.Normal, null!, Location); } return result; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintImportDeclaration.cs b/Jint/Runtime/Interpreter/Statements/JintImportDeclaration.cs index d1bbbcb5a2..d7a984fc94 100644 --- a/Jint/Runtime/Interpreter/Statements/JintImportDeclaration.cs +++ b/Jint/Runtime/Interpreter/Statements/JintImportDeclaration.cs @@ -1,6 +1,4 @@ -#nullable enable - -using Esprima.Ast; +using Esprima.Ast; namespace Jint.Runtime.Interpreter.Statements; @@ -17,7 +15,7 @@ protected override void Initialize(EvaluationContext context) protected override Completion ExecuteInternal(EvaluationContext context) { // just to ensure module context or valid - context.Engine.GetActiveScriptOrModule().AsModule(context.Engine, context.LastSyntaxNode.Location); + context.Engine.GetActiveScriptOrModule().AsModule(context.Engine, context.LastSyntaxNode!.Location); return Completion.Empty(); } } diff --git a/Jint/Runtime/Interpreter/Statements/JintLabeledStatement.cs b/Jint/Runtime/Interpreter/Statements/JintLabeledStatement.cs index 31abff90ce..2cc89e74a7 100644 --- a/Jint/Runtime/Interpreter/Statements/JintLabeledStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintLabeledStatement.cs @@ -4,8 +4,8 @@ namespace Jint.Runtime.Interpreter.Statements { internal sealed class JintLabeledStatement : JintStatement { - private JintStatement _body; - private string _labelName; + private JintStatement _body = null!; + private string? _labelName; public JintLabeledStatement(LabeledStatement statement) : base(statement) { @@ -32,4 +32,4 @@ protected override Completion ExecuteInternal(EvaluationContext context) return result; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintReturnStatement.cs b/Jint/Runtime/Interpreter/Statements/JintReturnStatement.cs index 044e8139f0..6b79afebe0 100644 --- a/Jint/Runtime/Interpreter/Statements/JintReturnStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintReturnStatement.cs @@ -9,7 +9,7 @@ namespace Jint.Runtime.Interpreter.Statements /// internal sealed class JintReturnStatement : JintStatement { - private JintExpression _argument; + private JintExpression? _argument; public JintReturnStatement(ReturnStatement statement) : base(statement) { @@ -28,4 +28,4 @@ protected override Completion ExecuteInternal(EvaluationContext context) return new Completion(CompletionType.Return, jsValue, null, Location); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintScript.cs b/Jint/Runtime/Interpreter/Statements/JintScript.cs index 25083bebe0..2a22f5bdb3 100644 --- a/Jint/Runtime/Interpreter/Statements/JintScript.cs +++ b/Jint/Runtime/Interpreter/Statements/JintScript.cs @@ -16,4 +16,4 @@ protected override Completion ExecuteInternal(EvaluationContext context) return _list.Execute(context); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintStatement.cs b/Jint/Runtime/Interpreter/Statements/JintStatement.cs index 5c97d97fea..594aff18e0 100644 --- a/Jint/Runtime/Interpreter/Statements/JintStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintStatement.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; using System.Runtime.CompilerServices; using Esprima; using Esprima.Ast; @@ -66,7 +66,7 @@ protected virtual void Initialize(EvaluationContext context) protected internal static JintStatement Build(Statement statement) { - JintStatement result = statement.Type switch + JintStatement? result = statement.Type switch { Nodes.BlockStatement => new JintBlockStatement((BlockStatement) statement), Nodes.ReturnStatement => new JintReturnStatement((ReturnStatement) statement), @@ -132,4 +132,4 @@ protected Completion NormalCompletion(JsValue value) return new Completion(CompletionType.Normal, value, _statement.Location); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintSwitchBlock.cs b/Jint/Runtime/Interpreter/Statements/JintSwitchBlock.cs index 310c3e4986..eba2bda610 100644 --- a/Jint/Runtime/Interpreter/Statements/JintSwitchBlock.cs +++ b/Jint/Runtime/Interpreter/Statements/JintSwitchBlock.cs @@ -9,7 +9,7 @@ namespace Jint.Runtime.Interpreter.Statements internal sealed class JintSwitchBlock { private readonly NodeList _switchBlock; - private JintSwitchCase[] _jintSwitchBlock; + private JintSwitchCase[] _jintSwitchBlock = Array.Empty(); private bool _initialized; public JintSwitchBlock(NodeList switchBlock) @@ -38,14 +38,14 @@ public Completion Execute(EvaluationContext context, JsValue input) var engine = context.Engine; JsValue v = Undefined.Instance; Location l = context.LastSyntaxNode.Location; - JintSwitchCase defaultCase = null; + JintSwitchCase? defaultCase = null; bool hit = false; for (var i = 0; i < (uint) _jintSwitchBlock.Length; i++) { var clause = _jintSwitchBlock[i]; - EnvironmentRecord oldEnv = null; + EnvironmentRecord? oldEnv = null; if (clause.LexicalDeclarations != null) { oldEnv = engine.ExecutionContext.LexicalEnvironment; @@ -89,7 +89,7 @@ public Completion Execute(EvaluationContext context, JsValue input) // do we need to execute the default case ? if (hit == false && defaultCase != null) { - EnvironmentRecord oldEnv = null; + EnvironmentRecord? oldEnv = null; if (defaultCase.LexicalDeclarations != null) { oldEnv = engine.ExecutionContext.LexicalEnvironment; @@ -119,8 +119,8 @@ public Completion Execute(EvaluationContext context, JsValue input) private sealed class JintSwitchCase { internal readonly JintStatementList Consequent; - internal readonly JintExpression Test; - internal readonly List LexicalDeclarations; + internal readonly JintExpression? Test; + internal readonly List? LexicalDeclarations; public JintSwitchCase(Engine engine, SwitchCase switchCase) { diff --git a/Jint/Runtime/Interpreter/Statements/JintSwitchStatement.cs b/Jint/Runtime/Interpreter/Statements/JintSwitchStatement.cs index f2c1cc3af5..a6e2d7ad05 100644 --- a/Jint/Runtime/Interpreter/Statements/JintSwitchStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintSwitchStatement.cs @@ -8,8 +8,8 @@ namespace Jint.Runtime.Interpreter.Statements /// internal sealed class JintSwitchStatement : JintStatement { - private JintSwitchBlock _switchBlock; - private JintExpression _discriminant; + private JintSwitchBlock _switchBlock = null!; + private JintExpression _discriminant = null!; public JintSwitchStatement(SwitchStatement statement) : base(statement) { @@ -34,4 +34,4 @@ protected override Completion ExecuteInternal(EvaluationContext context) return r; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintThrowStatement.cs b/Jint/Runtime/Interpreter/Statements/JintThrowStatement.cs index 169c97142d..9c3485ea82 100644 --- a/Jint/Runtime/Interpreter/Statements/JintThrowStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintThrowStatement.cs @@ -8,7 +8,7 @@ namespace Jint.Runtime.Interpreter.Statements /// internal sealed class JintThrowStatement : JintStatement { - private JintExpression _argument; + private JintExpression _argument = null!; public JintThrowStatement(ThrowStatement statement) : base(statement) { diff --git a/Jint/Runtime/Interpreter/Statements/JintTryStatement.cs b/Jint/Runtime/Interpreter/Statements/JintTryStatement.cs index 9c510d75c7..015aa72484 100644 --- a/Jint/Runtime/Interpreter/Statements/JintTryStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintTryStatement.cs @@ -9,9 +9,9 @@ namespace Jint.Runtime.Interpreter.Statements /// internal sealed class JintTryStatement : JintStatement { - private JintBlockStatement _block; - private JintStatement _catch; - private JintBlockStatement _finalizer; + private JintBlockStatement _block = null!; + private JintStatement? _catch; + private JintBlockStatement? _finalizer; public JintTryStatement(TryStatement statement) : base(statement) { @@ -37,15 +37,15 @@ protected override Completion ExecuteInternal(EvaluationContext context) if (b.Type == CompletionType.Throw) { - // initialize lazily - if (_statement.Handler is not null && _catch is null) - { - _catch = Build(_statement.Handler.Body); - } - // execute catch if (_statement.Handler is not null) { + // initialize lazily + if (_catch is null) + { + _catch = Build(_statement.Handler.Body); + } + // https://tc39.es/ecma262/#sec-runtime-semantics-catchclauseevaluation var thrownValue = b.Value; diff --git a/Jint/Runtime/Interpreter/Statements/JintVariableDeclaration.cs b/Jint/Runtime/Interpreter/Statements/JintVariableDeclaration.cs index 976beeeda4..f9f34396c1 100644 --- a/Jint/Runtime/Interpreter/Statements/JintVariableDeclaration.cs +++ b/Jint/Runtime/Interpreter/Statements/JintVariableDeclaration.cs @@ -10,14 +10,14 @@ internal sealed class JintVariableDeclaration : JintStatement(); private sealed class ResolvedDeclaration { - internal JintExpression Left; - internal BindingPattern LeftPattern; - internal JintExpression Init; - internal JintIdentifierExpression LeftIdentifierExpression; + internal JintExpression? Left; + internal BindingPattern? LeftPattern; + internal JintExpression? Init; + internal JintIdentifierExpression? LeftIdentifierExpression; internal bool EvalOrArguments; } @@ -33,9 +33,9 @@ protected override void Initialize(EvaluationContext context) { var declaration = _statement.Declarations[i]; - JintExpression left = null; - JintExpression init = null; - BindingPattern bindingPattern = null; + JintExpression? left = null; + JintExpression? init = null; + BindingPattern? bindingPattern = null; if (declaration.Id is BindingPattern bp) { @@ -110,7 +110,7 @@ protected override Completion ExecuteInternal(EvaluationContext context) declaration.EvalOrArguments) is null) { // slow path - var lhs = (Reference) declaration.Left.Evaluate(context).Value; + var lhs = (Reference) declaration.Left!.Evaluate(context).Value; lhs.AssertValid(engine.Realm); var completion = declaration.Init.GetValue(context); @@ -130,4 +130,4 @@ protected override Completion ExecuteInternal(EvaluationContext context) return VoidCompletion; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/Statements/JintWhileStatement.cs b/Jint/Runtime/Interpreter/Statements/JintWhileStatement.cs index 93bac7d250..540febf7cd 100644 --- a/Jint/Runtime/Interpreter/Statements/JintWhileStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintWhileStatement.cs @@ -9,9 +9,9 @@ namespace Jint.Runtime.Interpreter.Statements /// internal sealed class JintWhileStatement : JintStatement { - private string _labelSetName; - private JintStatement _body; - private JintExpression _test; + private string? _labelSetName; + private JintStatement _body = null!; + private JintExpression _test = null!; public JintWhileStatement(WhileStatement statement) : base(statement) { diff --git a/Jint/Runtime/Interpreter/Statements/JintWithStatement.cs b/Jint/Runtime/Interpreter/Statements/JintWithStatement.cs index 55cb12d7e4..817f925abd 100644 --- a/Jint/Runtime/Interpreter/Statements/JintWithStatement.cs +++ b/Jint/Runtime/Interpreter/Statements/JintWithStatement.cs @@ -9,8 +9,8 @@ namespace Jint.Runtime.Interpreter.Statements /// internal sealed class JintWithStatement : JintStatement { - private JintStatement _body; - private JintExpression _object; + private JintStatement _body = null!; + private JintExpression _object = null!; public JintWithStatement(WithStatement statement) : base(statement) { @@ -48,4 +48,4 @@ protected override Completion ExecuteInternal(EvaluationContext context) return c; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Intrinsics.cs b/Jint/Runtime/Intrinsics.cs index d2c32225aa..672238f926 100644 --- a/Jint/Runtime/Intrinsics.cs +++ b/Jint/Runtime/Intrinsics.cs @@ -42,56 +42,56 @@ public sealed class Intrinsics private readonly Realm _realm; // lazy properties - private ThrowTypeError _throwTypeError; - private AggregateErrorConstructor _aggregateError; - private ErrorConstructor _error; - private ErrorConstructor _evalError; - private ErrorConstructor _rangeError; - private ErrorConstructor _referenceError; - private ErrorConstructor _syntaxError; - private ErrorConstructor _typeError; - private ErrorConstructor _uriError; - private WeakMapConstructor _weakMap; - private WeakSetConstructor _weakSet; - private PromiseConstructor _promise; - private ProxyConstructor _proxy; - private ReflectInstance _reflect; - private EvalFunctionInstance _eval; - private DateConstructor _date; - private IteratorPrototype _iteratorPrototype; - private MathInstance _math; - private JsonInstance _json; - private SymbolConstructor _symbol; - private RegExpConstructor _regExp; - private RegExpStringIteratorPrototype _regExpStringIteratorPrototype; - private NumberConstructor _number; - private BigIntConstructor _bigInt; - private StringConstructor _string; - private StringIteratorPrototype _stringIteratorPrototype; - private MapConstructor _map; - private MapIteratorPrototype _mapIteratorPrototype; - private SetConstructor _set; - private SetIteratorPrototype _setIteratorPrototype; - private ArrayConstructor _array; - private ArrayIteratorPrototype _arrayIteratorPrototype; - private BooleanConstructor _boolean; - private ArrayBufferConstructor _arrayBufferConstructor; - private DataViewConstructor _dataView; - - private IntrinsicTypedArrayConstructor _typedArray; - private Int8ArrayConstructor _int8Array; - private Uint8ArrayConstructor _uint8Array; - private Uint8ClampedArrayConstructor _uint8ClampedArray; - private Int16ArrayConstructor _int16Array; - private Uint16ArrayConstructor _uint16Array; - private Int32ArrayConstructor _int32Array; - private Uint32ArrayConstructor _uint32Array; - private BigInt64ArrayConstructor _bigInt64Array; - private BigUint64ArrayConstructor _bigUint64Array; - private Float32ArrayConstructor _float32Array; - private Float64ArrayConstructor _float64Array; - - private ShadowRealmConstructor _shadowRealm; + private ThrowTypeError? _throwTypeError; + private AggregateErrorConstructor? _aggregateError; + private ErrorConstructor? _error; + private ErrorConstructor? _evalError; + private ErrorConstructor? _rangeError; + private ErrorConstructor? _referenceError; + private ErrorConstructor? _syntaxError; + private ErrorConstructor? _typeError; + private ErrorConstructor? _uriError; + private WeakMapConstructor? _weakMap; + private WeakSetConstructor? _weakSet; + private PromiseConstructor? _promise; + private ProxyConstructor? _proxy; + private ReflectInstance? _reflect; + private EvalFunctionInstance? _eval; + private DateConstructor? _date; + private IteratorPrototype? _iteratorPrototype; + private MathInstance? _math; + private JsonInstance? _json; + private SymbolConstructor? _symbol; + private RegExpConstructor? _regExp; + private RegExpStringIteratorPrototype? _regExpStringIteratorPrototype; + private NumberConstructor? _number; + private BigIntConstructor? _bigInt; + private StringConstructor? _string; + private StringIteratorPrototype? _stringIteratorPrototype; + private MapConstructor? _map; + private MapIteratorPrototype? _mapIteratorPrototype; + private SetConstructor? _set; + private SetIteratorPrototype? _setIteratorPrototype; + private ArrayConstructor? _array; + private ArrayIteratorPrototype? _arrayIteratorPrototype; + private BooleanConstructor? _boolean; + private ArrayBufferConstructor? _arrayBufferConstructor; + private DataViewConstructor? _dataView; + + private IntrinsicTypedArrayConstructor? _typedArray; + private Int8ArrayConstructor? _int8Array; + private Uint8ArrayConstructor? _uint8Array; + private Uint8ClampedArrayConstructor? _uint8ClampedArray; + private Int16ArrayConstructor? _int16Array; + private Uint16ArrayConstructor? _uint16Array; + private Int32ArrayConstructor? _int32Array; + private Uint32ArrayConstructor? _uint32Array; + private BigInt64ArrayConstructor? _bigInt64Array; + private BigUint64ArrayConstructor? _bigUint64Array; + private Float32ArrayConstructor? _float32Array; + private Float64ArrayConstructor? _float64Array; + + private ShadowRealmConstructor? _shadowRealm; internal Intrinsics(Engine engine, Realm realm) { diff --git a/Jint/Runtime/JavaScriptException.cs b/Jint/Runtime/JavaScriptException.cs index 0dcfb4e610..1d6f6bdc86 100644 --- a/Jint/Runtime/JavaScriptException.cs +++ b/Jint/Runtime/JavaScriptException.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima; using Jint.Native; using Jint.Native.Error; @@ -10,19 +8,19 @@ namespace Jint.Runtime; public class JavaScriptException : JintException { - private static string GetMessage(JsValue error) + private static string? GetMessage(JsValue? error) { - string? ret; + string? ret = null; if (error is ObjectInstance oi) { ret = oi.Get(CommonProperties.Message).ToString(); } - else + else if (error is not null) { - ret = null; + ret = TypeConverter.ToString(error); } - return ret ?? TypeConverter.ToString(error); + return ret; } private readonly JavaScriptErrorWrapperException _jsErrorException; @@ -86,7 +84,7 @@ internal void SetCallstack(Engine engine, Location location, bool overwriteExist Location = location; var errObj = Error.IsObject() ? Error.AsObject() : null; - if (errObj == null) + if (errObj is null) { _callStack = engine.CallStack.BuildCallStackString(location); return; diff --git a/Jint/Runtime/JintException.cs b/Jint/Runtime/JintException.cs index 14bac32d72..150a7263d8 100644 --- a/Jint/Runtime/JintException.cs +++ b/Jint/Runtime/JintException.cs @@ -16,11 +16,11 @@ protected JintException(SerializationInfo info, StreamingContext context) : base { } - protected JintException(string message) : base(message) + protected JintException(string? message) : base(message) { } - protected JintException(string message, Exception innerException) : base(message, innerException) + protected JintException(string? message, Exception? innerException) : base(message, innerException) { } } diff --git a/Jint/Runtime/KnownKeys.cs b/Jint/Runtime/KnownKeys.cs index 56df7bffae..9121f2a1bc 100644 --- a/Jint/Runtime/KnownKeys.cs +++ b/Jint/Runtime/KnownKeys.cs @@ -8,4 +8,4 @@ internal static class KnownKeys internal static readonly Key Done = "done"; internal static readonly Key Value = "value"; } -} \ No newline at end of file +} diff --git a/Jint/Runtime/MemoryLimitExceededException.cs b/Jint/Runtime/MemoryLimitExceededException.cs index 60f0272aad..fa6721cacc 100644 --- a/Jint/Runtime/MemoryLimitExceededException.cs +++ b/Jint/Runtime/MemoryLimitExceededException.cs @@ -1,4 +1,4 @@ -namespace Jint.Runtime +namespace Jint.Runtime { public sealed class MemoryLimitExceededException : JintException { diff --git a/Jint/Runtime/Modules/BuilderModuleRecord.cs b/Jint/Runtime/Modules/BuilderModuleRecord.cs index 94370fe48b..747571332f 100644 --- a/Jint/Runtime/Modules/BuilderModuleRecord.cs +++ b/Jint/Runtime/Modules/BuilderModuleRecord.cs @@ -1,4 +1,4 @@ -using Esprima.Ast; +using Esprima.Ast; using Jint.Native; namespace Jint.Runtime.Modules; @@ -10,7 +10,7 @@ internal sealed class BuilderModuleRecord : SourceTextModuleRecord { private List> _exportBuilderDeclarations = new(); - internal BuilderModuleRecord(Engine engine, Realm realm, Module source, string location, bool async) + internal BuilderModuleRecord(Engine engine, Realm realm, Module source, string? location, bool async) : base(engine, realm, source, location, async) { } diff --git a/Jint/Runtime/Modules/CyclicModuleRecord.cs b/Jint/Runtime/Modules/CyclicModuleRecord.cs index 59183e4c63..63e99458a7 100644 --- a/Jint/Runtime/Modules/CyclicModuleRecord.cs +++ b/Jint/Runtime/Modules/CyclicModuleRecord.cs @@ -1,4 +1,6 @@ -using Esprima.Ast; +#nullable disable + +using Esprima.Ast; using Jint.Native; using Jint.Native.Promise; using Jint.Runtime.Descriptors; diff --git a/Jint/Runtime/Modules/DefaultModuleLoader.cs b/Jint/Runtime/Modules/DefaultModuleLoader.cs index 0cd465a984..83a944323f 100644 --- a/Jint/Runtime/Modules/DefaultModuleLoader.cs +++ b/Jint/Runtime/Modules/DefaultModuleLoader.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima; using Esprima.Ast; diff --git a/Jint/Runtime/Modules/FailFastModuleLoader.cs b/Jint/Runtime/Modules/FailFastModuleLoader.cs index ad2e8b61e9..a89163809c 100644 --- a/Jint/Runtime/Modules/FailFastModuleLoader.cs +++ b/Jint/Runtime/Modules/FailFastModuleLoader.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima.Ast; namespace Jint.Runtime.Modules; diff --git a/Jint/Runtime/Modules/IModuleLoader.cs b/Jint/Runtime/Modules/IModuleLoader.cs index 375e3b8f83..672cefb1e3 100644 --- a/Jint/Runtime/Modules/IModuleLoader.cs +++ b/Jint/Runtime/Modules/IModuleLoader.cs @@ -1,5 +1,3 @@ -#nullable enable - using Esprima.Ast; namespace Jint.Runtime.Modules; diff --git a/Jint/Runtime/Modules/ModuleNamespace.cs b/Jint/Runtime/Modules/ModuleNamespace.cs index 12e032efbf..6523b87a5d 100644 --- a/Jint/Runtime/Modules/ModuleNamespace.cs +++ b/Jint/Runtime/Modules/ModuleNamespace.cs @@ -1,4 +1,6 @@ -using Jint.Collections; +#nullable disable + +using Jint.Collections; using Jint.Native; using Jint.Native.Array; using Jint.Native.Object; diff --git a/Jint/Runtime/Modules/ModuleRecord.cs b/Jint/Runtime/Modules/ModuleRecord.cs index 48939b995f..21b27460c0 100644 --- a/Jint/Runtime/Modules/ModuleRecord.cs +++ b/Jint/Runtime/Modules/ModuleRecord.cs @@ -1,4 +1,6 @@ -using Jint.Native; +#nullable disable + +using Jint.Native; using Jint.Native.Object; using Jint.Runtime.Environments; diff --git a/Jint/Runtime/Modules/ModuleResolutionException.cs b/Jint/Runtime/Modules/ModuleResolutionException.cs index 5ec212ac04..2da629c985 100644 --- a/Jint/Runtime/Modules/ModuleResolutionException.cs +++ b/Jint/Runtime/Modules/ModuleResolutionException.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Jint.Runtime.Modules; public sealed class ModuleResolutionException : JintException diff --git a/Jint/Runtime/Modules/ModuleStatus.cs b/Jint/Runtime/Modules/ModuleStatus.cs index 0c1ebbbabc..10e9657edf 100644 --- a/Jint/Runtime/Modules/ModuleStatus.cs +++ b/Jint/Runtime/Modules/ModuleStatus.cs @@ -1,4 +1,4 @@ -namespace Jint.Runtime.Modules; +namespace Jint.Runtime.Modules; internal enum ModuleStatus { @@ -8,4 +8,4 @@ internal enum ModuleStatus Evaluating, EvaluatingAsync, Evaluated -} \ No newline at end of file +} diff --git a/Jint/Runtime/Modules/ResolvedSpecifier.cs b/Jint/Runtime/Modules/ResolvedSpecifier.cs index 2af3bf12ad..70bfe45f43 100644 --- a/Jint/Runtime/Modules/ResolvedSpecifier.cs +++ b/Jint/Runtime/Modules/ResolvedSpecifier.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Jint.Runtime.Modules; public record ResolvedSpecifier(string Specifier, string Key, Uri? Uri, SpecifierType Type); diff --git a/Jint/Runtime/Modules/SourceTextModuleRecord.cs b/Jint/Runtime/Modules/SourceTextModuleRecord.cs index bb2368f11e..903d4769ff 100644 --- a/Jint/Runtime/Modules/SourceTextModuleRecord.cs +++ b/Jint/Runtime/Modules/SourceTextModuleRecord.cs @@ -1,4 +1,6 @@ -using Esprima.Ast; +#nullable disable + +using Esprima.Ast; using Jint.Native.Object; using Jint.Native.Promise; using Jint.Runtime.Environments; diff --git a/Jint/Runtime/Modules/SpecifierType.cs b/Jint/Runtime/Modules/SpecifierType.cs index 3f428cd1b9..3dc1fdf93c 100644 --- a/Jint/Runtime/Modules/SpecifierType.cs +++ b/Jint/Runtime/Modules/SpecifierType.cs @@ -1,4 +1,4 @@ -namespace Jint.Runtime.Modules; +namespace Jint.Runtime.Modules; public enum SpecifierType { diff --git a/Jint/Runtime/OrderedDictionary.cs b/Jint/Runtime/OrderedDictionary.cs index fc25fa1cf1..69182b9a78 100644 --- a/Jint/Runtime/OrderedDictionary.cs +++ b/Jint/Runtime/OrderedDictionary.cs @@ -1,3 +1,5 @@ +#nullable disable + // based on https://github.com/jehugaleahsa/truncon.collections.OrderedDictionary // https://github.com/jehugaleahsa/truncon.collections.OrderedDictionary/blob/master/UNLICENSE.txt diff --git a/Jint/Runtime/PromiseRejectedException.cs b/Jint/Runtime/PromiseRejectedException.cs index 1caab82b49..4433d96a02 100644 --- a/Jint/Runtime/PromiseRejectedException.cs +++ b/Jint/Runtime/PromiseRejectedException.cs @@ -11,4 +11,4 @@ public PromiseRejectedException(JsValue value) : base($"Promise was rejected wit public JsValue RejectedValue { get; } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/RangeErrorException.cs b/Jint/Runtime/RangeErrorException.cs index 4f9ad96d0d..f063b6aab7 100644 --- a/Jint/Runtime/RangeErrorException.cs +++ b/Jint/Runtime/RangeErrorException.cs @@ -1,4 +1,4 @@ -namespace Jint.Runtime +namespace Jint.Runtime { /// /// Workaround for situation where engine is not easily accessible. @@ -9,4 +9,4 @@ public RangeErrorException(string message) : base(message) { } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Realm.cs b/Jint/Runtime/Realm.cs index 157de69059..32039c0ef7 100644 --- a/Jint/Runtime/Realm.cs +++ b/Jint/Runtime/Realm.cs @@ -21,21 +21,21 @@ public Realm() /// /// The intrinsic values used by code associated with this realm. /// - public Intrinsics Intrinsics { get; internal set; } + public Intrinsics Intrinsics { get; internal set; } = null!; /// /// The global object for this realm. /// - public ObjectInstance GlobalObject { get; internal set; } + public ObjectInstance GlobalObject { get; internal set; } = null!; /// /// The global environment for this realm. /// - public GlobalEnvironmentRecord GlobalEnv { get; internal set; } + public GlobalEnvironmentRecord GlobalEnv { get; internal set; } = null!; /// /// Field reserved for use by hosts that need to associate additional information with a Realm Record. /// - public object HostDefined { get; set; } + public object? HostDefined { get; set; } } } diff --git a/Jint/Runtime/RecursionDepthOverflowException.cs b/Jint/Runtime/RecursionDepthOverflowException.cs index c26d17af81..1d4aa6057a 100644 --- a/Jint/Runtime/RecursionDepthOverflowException.cs +++ b/Jint/Runtime/RecursionDepthOverflowException.cs @@ -1,4 +1,4 @@ -using Jint.Runtime.CallStack; +using Jint.Runtime.CallStack; namespace Jint.Runtime { diff --git a/Jint/Runtime/References/Reference.cs b/Jint/Runtime/References/Reference.cs index 06f31badd4..b869637cdf 100644 --- a/Jint/Runtime/References/Reference.cs +++ b/Jint/Runtime/References/Reference.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.CompilerServices; using Jint.Native; using Jint.Runtime.Environments; @@ -14,9 +14,9 @@ public sealed class Reference private JsValue _baseValue; private JsValue _property; internal bool _strict; - private JsValue _thisValue; + private JsValue? _thisValue; - public Reference(JsValue baseValue, JsValue property, bool strict, JsValue thisValue = null) + public Reference(JsValue baseValue, JsValue property, bool strict, JsValue? thisValue = null) { _baseValue = baseValue; _property = property; @@ -60,13 +60,13 @@ public JsValue GetThisValue() { if (IsSuperReference()) { - return _thisValue; + return _thisValue!; } return GetBase(); } - internal Reference Reassign(JsValue baseValue, JsValue name, bool strict, JsValue thisValue) + internal Reference Reassign(JsValue baseValue, JsValue name, bool strict, JsValue? thisValue) { _baseValue = baseValue; _property = name; diff --git a/Jint/Runtime/StatementsCountOverflowException.cs b/Jint/Runtime/StatementsCountOverflowException.cs index ce1fc8e85b..dffeba5465 100644 --- a/Jint/Runtime/StatementsCountOverflowException.cs +++ b/Jint/Runtime/StatementsCountOverflowException.cs @@ -1,6 +1,6 @@ -namespace Jint.Runtime +namespace Jint.Runtime { - public sealed class StatementsCountOverflowException : JintException + public sealed class StatementsCountOverflowException : JintException { public StatementsCountOverflowException() : base("The maximum number of statements executed have been reached.") { diff --git a/Jint/Runtime/TypeConverter.cs b/Jint/Runtime/TypeConverter.cs index 572280f0e1..f050cbb6a1 100644 --- a/Jint/Runtime/TypeConverter.cs +++ b/Jint/Runtime/TypeConverter.cs @@ -952,7 +952,7 @@ private static string ToStringNonString(JsValue o) case InternalTypes.Null: return Null.Text; case InternalTypes.Object when o is IObjectWrapper p: - return p.Target?.ToString(); + return p.Target?.ToString()!; default: return ToString(ToPrimitive(o, Types.String)); } @@ -1050,7 +1050,7 @@ internal static IEnumerable FindBestMatch( MethodDescriptor[] methods, Func argumentProvider) { - List matchingByParameterCount = null; + List? matchingByParameterCount = null; foreach (var method in methods) { var parameterInfos = method.Parameters; @@ -1142,7 +1142,7 @@ internal static AssignableResult IsAssignableToGenericType(Type givenType, Type { if (givenType is null) { - return new AssignableResult(-1, null); + return new AssignableResult(-1, typeof(void)); } if (!genericType.IsConstructedGenericType) @@ -1251,7 +1251,7 @@ jsValue is JsNumber jsNumber return 1; } - if (jsValue.IsArray() && objectValueType.IsArray) + if (jsValue.IsArray() && objectValueType!.IsArray) { // we have potential, TODO if we'd know JS array's internal type we could have exact match return 2; @@ -1260,7 +1260,7 @@ jsValue is JsNumber jsNumber // not sure the best point to start generic type tests if (paramType.IsGenericParameter) { - var genericTypeAssignmentScore = IsAssignableToGenericType(objectValueType, paramType); + var genericTypeAssignmentScore = IsAssignableToGenericType(objectValueType!, paramType); if (genericTypeAssignmentScore.Score != -1) { return genericTypeAssignmentScore.Score; @@ -1273,7 +1273,7 @@ jsValue is JsNumber jsNumber return 3; } - foreach (var m in objectValueType.GetOperatorOverloadMethods()) + foreach (var m in objectValueType!.GetOperatorOverloadMethods()) { if (paramType.IsAssignableFrom(m.ReturnType) && m.Name is "op_Implicit" or "op_Explicit") { diff --git a/Jint/Runtime/TypeErrorException.cs b/Jint/Runtime/TypeErrorException.cs index bad3333ae2..30486d4b64 100644 --- a/Jint/Runtime/TypeErrorException.cs +++ b/Jint/Runtime/TypeErrorException.cs @@ -1,12 +1,12 @@ -namespace Jint.Runtime +namespace Jint.Runtime { /// /// Workaround for situation where engine is not easily accessible. /// internal sealed class TypeErrorException : JintException { - public TypeErrorException(string message) : base(message) + public TypeErrorException(string? message) : base(message) { } } -} \ No newline at end of file +} diff --git a/Jint/StrictModeScope.cs b/Jint/StrictModeScope.cs index 3a9a39b038..ff70038145 100644 --- a/Jint/StrictModeScope.cs +++ b/Jint/StrictModeScope.cs @@ -1,4 +1,4 @@ -namespace Jint +namespace Jint { public readonly struct StrictModeScope : IDisposable {