diff --git a/Source/JavaScriptCore/API/APICallbackFunction.h b/Source/JavaScriptCore/API/APICallbackFunction.h index 616924b97942..0adfb9082814 100644 --- a/Source/JavaScriptCore/API/APICallbackFunction.h +++ b/Source/JavaScriptCore/API/APICallbackFunction.h @@ -48,10 +48,10 @@ EncodedJSValue APICallbackFunction::callImpl(JSGlobalObject* globalObject, CallF JSObjectRef functionRef = toRef(callFrame->jsCallee()); JSObjectRef thisObjRef = toRef(jsCast(callFrame->thisValue().toThis(globalObject, ECMAMode::sloppy()))); - int argumentCount = static_cast(callFrame->argumentCount()); + size_t argumentCount = callFrame->argumentCount(); Vector arguments; arguments.reserveInitialCapacity(argumentCount); - for (int i = 0; i < argumentCount; i++) + for (size_t i = 0; i < argumentCount; i++) arguments.uncheckedAppend(toRef(globalObject, callFrame->uncheckedArgument(i))); JSValueRef exception = nullptr; diff --git a/Source/JavaScriptCore/API/JSAPIGlobalObject.mm b/Source/JavaScriptCore/API/JSAPIGlobalObject.mm index e9995bf68457..49da4e2150bd 100644 --- a/Source/JavaScriptCore/API/JSAPIGlobalObject.mm +++ b/Source/JavaScriptCore/API/JSAPIGlobalObject.mm @@ -207,12 +207,12 @@ JSScript* jsScript = static_cast(script); - JSSourceCode* source = [jsScript jsSourceCode]; + JSSourceCode* source = jsScript.jsSourceCode; if (UNLIKELY([jsScript type] != kJSScriptTypeModule)) return rejectPromise("The JSScript that was provided did not have expected type of kJSScriptTypeModule."_s); - NSURL *sourceURL = [jsScript sourceURL]; - String oldModuleKey { [sourceURL absoluteString] }; + NSURL *sourceURL = jsScript.sourceURL; + String oldModuleKey { sourceURL.absoluteString }; if (UNLIKELY(Identifier::fromString(vm, oldModuleKey) != moduleKey)) return rejectPromise(makeString("The same JSScript was provided for two different identifiers, previously: ", oldModuleKey, " and now: ", moduleKey.string())); @@ -225,10 +225,10 @@ return encodedJSUndefined(); }); - [[context moduleLoaderDelegate] context:context fetchModuleForIdentifier:[::JSValue valueWithJSValueRef:toRef(globalObject, key) inContext:context] withResolveHandler:[::JSValue valueWithJSValueRef:toRef(globalObject, resolve) inContext:context] andRejectHandler:[::JSValue valueWithJSValueRef:toRef(globalObject, reject) inContext:context]]; + [context.moduleLoaderDelegate context:context fetchModuleForIdentifier:[::JSValue valueWithJSValueRef:toRef(globalObject, key) inContext:context] withResolveHandler:[::JSValue valueWithJSValueRef:toRef(globalObject, resolve) inContext:context] andRejectHandler:[::JSValue valueWithJSValueRef:toRef(globalObject, reject) inContext:context]]; if (context.exception) { scope.release(); - promise->reject(globalObject, toJS(globalObject, [context.exception JSValueRef])); + promise->reject(globalObject, toJS(globalObject, context.exception.JSValueRef)); context.exception = nil; } return promise; @@ -254,7 +254,7 @@ auto scope = DECLARE_THROW_SCOPE(vm); JSContext *context = [JSContext contextWithJSGlobalContextRef:toGlobalRef(globalObject)]; - id moduleLoaderDelegate = [context moduleLoaderDelegate]; + id moduleLoaderDelegate = context.moduleLoaderDelegate; NSURL *url = nil; if ([moduleLoaderDelegate respondsToSelector:@selector(willEvaluateModule:)] || [moduleLoaderDelegate respondsToSelector:@selector(didEvaluateModule:)]) { @@ -282,7 +282,7 @@ VM& vm = this->vm(); auto scope = DECLARE_THROW_SCOPE(vm); - Identifier key = Identifier::fromString(vm, String { [[script sourceURL] absoluteString] }); + Identifier key = Identifier::fromString(vm, String { script.sourceURL.absoluteString }); JSInternalPromise* promise = importModule(this, key, jsUndefined(), jsUndefined(), jsUndefined()); RETURN_IF_EXCEPTION(scope, { }); auto* result = JSPromise::create(vm, this->promiseStructure()); diff --git a/Source/JavaScriptCore/API/JSContext.mm b/Source/JavaScriptCore/API/JSContext.mm index 887974b84aa0..6143f94a0a8f 100644 --- a/Source/JavaScriptCore/API/JSContext.mm +++ b/Source/JavaScriptCore/API/JSContext.mm @@ -63,9 +63,9 @@ - (JSGlobalContextRef)JSGlobalContextRef - (void)ensureWrapperMap { - if (!toJS([self JSGlobalContextRef])->wrapperMap()) { + if (!toJS(self.JSGlobalContextRef)->wrapperMap()) { // The map will be retained by the GlobalObject in initialization. - [[[JSWrapperMap alloc] initWithGlobalContextRef:[self JSGlobalContextRef]] release]; + [[[JSWrapperMap alloc] initWithGlobalContextRef:self.JSGlobalContextRef] release]; } } @@ -110,7 +110,7 @@ - (JSValue *)evaluateScript:(NSString *)script withSourceURL:(NSURL *)sourceURL { JSValueRef exceptionValue = nullptr; auto scriptJS = OpaqueJSString::tryCreate(script); - auto sourceURLJS = OpaqueJSString::tryCreate([sourceURL absoluteString]); + auto sourceURLJS = OpaqueJSString::tryCreate(sourceURL.absoluteString); JSValueRef result = JSEvaluateScript(m_context, scriptJS.get(), nullptr, sourceURLJS.get(), 0, &exceptionValue); if (exceptionValue) @@ -126,7 +126,7 @@ - (JSValue *)evaluateJSScript:(JSScript *)script if (script.type == kJSScriptTypeProgram) { JSValueRef exceptionValue = nullptr; - JSC::SourceCode sourceCode = [script sourceCode]; + JSC::SourceCode sourceCode = script.sourceCode; JSValueRef result = JSEvaluateScriptInternal(locker, m_context, nullptr, sourceCode, &exceptionValue); if (exceptionValue) @@ -162,7 +162,7 @@ - (JSValue *)dependencyIdentifiersForModuleJSScript:(JSScript *)script } auto scope = DECLARE_CATCH_SCOPE(vm); - JSC::JSArray* result = globalObject->moduleLoader()->dependencyKeysIfEvaluated(globalObject, JSC::jsString(vm, String([[script sourceURL] absoluteString]))); + JSC::JSArray* result = globalObject->moduleLoader()->dependencyKeysIfEvaluated(globalObject, JSC::jsString(vm, String(script.sourceURL.absoluteString))); if (scope.exception()) { JSValueRef exceptionValue = toRef(globalObject, scope.exception()->value()); scope.clearException(); @@ -329,12 +329,12 @@ @implementation JSContext(SubscriptSupport) - (JSValue *)objectForKeyedSubscript:(id)key { - return [self globalObject][key]; + return self.globalObject[key]; } - (void)setObject:(id)object forKeyedSubscript:(NSObject *)key { - [self globalObject][key] = object; + self.globalObject[key] = object; } @end @@ -400,7 +400,7 @@ - (void)endCallbackWithData:(CallbackData *)callbackData - (JSValue *)wrapperForObjCObject:(id)object { JSC::JSLockHolder locker(toJS(m_context)); - return [[self wrapperMap] jsWrapperForObject:object inContext:self]; + return [self.wrapperMap jsWrapperForObject:object inContext:self]; } - (JSWrapperMap *)wrapperMap @@ -411,7 +411,7 @@ - (JSWrapperMap *)wrapperMap - (JSValue *)wrapperForJSObject:(JSValueRef)value { JSC::JSLockHolder locker(toJS(m_context)); - return [[self wrapperMap] objcWrapperForJSValueRef:value inContext:self]; + return [self.wrapperMap objcWrapperForJSValueRef:value inContext:self]; } + (JSContext *)contextWithJSGlobalContextRef:(JSGlobalContextRef)globalContext diff --git a/Source/JavaScriptCore/API/JSContextInternal.h b/Source/JavaScriptCore/API/JSContextInternal.h index 44c5f58e3ac1..e75f6dcc99ec 100644 --- a/Source/JavaScriptCore/API/JSContextInternal.h +++ b/Source/JavaScriptCore/API/JSContextInternal.h @@ -51,7 +51,7 @@ struct CallbackData { - (void)beginCallbackWithData:(CallbackData *)callbackData calleeValue:(JSValueRef)calleeValue thisValue:(JSValueRef)thisValue argumentCount:(size_t)argumentCount arguments:(const JSValueRef *)arguments; - (void)endCallbackWithData:(CallbackData *)callbackData; -- (JSWrapperMap *)wrapperMap; +@property (nonatomic, readonly, strong) JSWrapperMap *wrapperMap; - (JSValue *)wrapperForObjCObject:(id)object; - (JSValue *)wrapperForJSObject:(JSValueRef)value; diff --git a/Source/JavaScriptCore/API/JSManagedValue.h b/Source/JavaScriptCore/API/JSManagedValue.h index 3ebc7a4bd918..f5a615ae0f70 100644 --- a/Source/JavaScriptCore/API/JSManagedValue.h +++ b/Source/JavaScriptCore/API/JSManagedValue.h @@ -64,7 +64,7 @@ NS_CLASS_AVAILABLE(10_9, 7_0) @abstract Create a JSManagedValue. @result The new JSManagedValue. */ -- (instancetype)initWithValue:(JSValue *)value; +- (instancetype)initWithValue:(JSValue *)value NS_DESIGNATED_INITIALIZER; /*! @property diff --git a/Source/JavaScriptCore/API/JSManagedValue.mm b/Source/JavaScriptCore/API/JSManagedValue.mm index 2c2c745a06d3..fa9e852e44a1 100644 --- a/Source/JavaScriptCore/API/JSManagedValue.mm +++ b/Source/JavaScriptCore/API/JSManagedValue.mm @@ -85,7 +85,7 @@ - (instancetype)initWithValue:(JSValue *)value if (!value) return self; - JSC::JSGlobalObject* globalObject = toJS([value.context JSGlobalContextRef]); + JSC::JSGlobalObject* globalObject = toJS(value.context.JSGlobalContextRef); auto& owner = managedValueHandleOwner(); JSC::Weak weak(globalObject, &owner, (__bridge void*)self); m_globalObject.swap(weak); @@ -96,7 +96,7 @@ - (instancetype)initWithValue:(JSValue *)value NSPointerFunctionsOptions integerOptions = NSPointerFunctionsOpaqueMemory | NSPointerFunctionsIntegerPersonality; m_owners = adoptNS([[NSMapTable alloc] initWithKeyOptions:weakIDOptions valueOptions:integerOptions capacity:1]); - JSC::JSValue jsValue = toJS(globalObject, [value JSValueRef]); + JSC::JSValue jsValue = toJS(globalObject, value.JSValueRef); if (jsValue.isObject()) m_weakValue.setObject(JSC::jsCast(jsValue.asCell()), owner, (__bridge void*)self); else if (jsValue.isString()) @@ -108,7 +108,7 @@ - (instancetype)initWithValue:(JSValue *)value - (void)dealloc { - JSVirtualMachine *virtualMachine = [[[self value] context] virtualMachine]; + JSVirtualMachine *virtualMachine = self.value.context.virtualMachine; if (virtualMachine) { auto copy = adoptNS([m_owners copy]); for (id owner in [copy keyEnumerator]) { diff --git a/Source/JavaScriptCore/API/JSScript.h b/Source/JavaScriptCore/API/JSScript.h index 12ccb0593ef9..b2f959ff0732 100644 --- a/Source/JavaScriptCore/API/JSScript.h +++ b/Source/JavaScriptCore/API/JSScript.h @@ -84,22 +84,22 @@ JSC_CLASS_AVAILABLE(macos(10.15), ios(13.0)) - (BOOL)cacheBytecodeWithError:(out NSError * _Nullable * _Nullable)error; /*! - @method + @property @abstract Returns true when evaluating this JSScript will use the bytecode cache. Returns false otherwise. */ -- (BOOL)isUsingBytecodeCache; +@property (nonatomic, getter=isUsingBytecodeCache, readonly) BOOL usingBytecodeCache; /*! - @method + @property @abstract Returns the JSScriptType of this JSScript. */ -- (JSScriptType)type; +@property (nonatomic, readonly) JSScriptType type; /*! - @method + @property @abstract Returns the sourceURL of this JSScript. */ -- (NSURL *)sourceURL; +@property (nonatomic, readonly, copy) NSURL *sourceURL; @end diff --git a/Source/JavaScriptCore/API/JSScript.mm b/Source/JavaScriptCore/API/JSScript.mm index 88c4292d61dd..67d46c04a635 100644 --- a/Source/JavaScriptCore/API/JSScript.mm +++ b/Source/JavaScriptCore/API/JSScript.mm @@ -72,7 +72,7 @@ static bool validateBytecodeCachePath(NSURL* cachePath, NSError** error) if (!cachePath) return true; - URL cachePathURL([cachePath absoluteURL]); + URL cachePathURL(cachePath.absoluteURL); if (!cachePathURL.isLocalFile()) { createError([NSString stringWithFormat:@"Cache path `%@` is not a local file", static_cast(cachePathURL)], error); return false; @@ -128,7 +128,7 @@ + (instancetype)scriptOfType:(JSScriptType)type memoryMappedFromASCIIFile:(NSURL if (!validateBytecodeCachePath(cachePath, error)) return nil; - URL filePathURL([filePath absoluteURL]); + URL filePathURL(filePath.absoluteURL); if (!filePathURL.isLocalFile()) return createError([NSString stringWithFormat:@"File path %@ is not a local file", static_cast(filePathURL)], error); @@ -157,7 +157,7 @@ - (void)readCache if (!m_cachePath) return; - String cacheFilename = [m_cachePath path]; + String cacheFilename = m_cachePath.get().path; auto fd = FileSystem::openAndLockFile(cacheFilename, FileSystem::FileOpenMode::Read, {FileSystem::FileLockMode::Exclusive, FileSystem::FileLockMode::Nonblocking}); if (!FileSystem::isHandleValid(fd)) @@ -172,7 +172,7 @@ - (void)readCache return; const uint8_t* fileData = reinterpret_cast(mappedFile.data()); - unsigned fileTotalSize = mappedFile.size(); + size_t fileTotalSize = mappedFile.size(); // Ensure we at least have a SHA1::Digest to read. if (fileTotalSize < sizeof(SHA1::Digest)) { @@ -180,7 +180,7 @@ - (void)readCache return; } - unsigned fileDataSize = fileTotalSize - sizeof(SHA1::Digest); + size_t fileDataSize = fileTotalSize - sizeof(SHA1::Digest); SHA1::Digest computedHash; SHA1 sha1; @@ -198,7 +198,7 @@ - (void)readCache Ref cachedBytecode = JSC::CachedBytecode::create(WTFMove(mappedFile)); JSC::VM& vm = *toJS([m_virtualMachine JSContextGroupRef]); - JSC::SourceCode sourceCode = [self sourceCode]; + JSC::SourceCode sourceCode = self.sourceCode; JSC::SourceCodeKey key = m_type == kJSScriptTypeProgram ? sourceCodeKeyForSerializedProgram(vm, sourceCode) : sourceCodeKeyForSerializedModule(vm, sourceCode); if (isCachedBytecodeStillValid(vm, cachedBytecode.copyRef(), key, m_type == kJSScriptTypeProgram ? JSC::SourceCodeType::ProgramType : JSC::SourceCodeType::ModuleType)) m_cachedBytecode = WTFMove(cachedBytecode); @@ -269,7 +269,7 @@ - (unsigned)hash JSC::JSLockHolder locker(vm); TextPosition startPosition { }; - String filename = String { [[self sourceURL] absoluteString] }; + String filename = String { self.sourceURL.absoluteString }; URL url = URL({ }, filename); auto type = m_type == kJSScriptTypeModule ? JSC::SourceProviderSourceType::Module : JSC::SourceProviderSourceType::Program; JSC::SourceOrigin origin(url); @@ -282,7 +282,7 @@ - (unsigned)hash { JSC::VM& vm = *toJS([m_virtualMachine JSContextGroupRef]); JSC::JSLockHolder locker(vm); - JSC::JSSourceCode* jsSourceCode = JSC::JSSourceCode::create(vm, [self sourceCode]); + JSC::JSSourceCode* jsSourceCode = JSC::JSSourceCode::create(vm, self.sourceCode); return jsSourceCode; } @@ -302,7 +302,7 @@ - (BOOL)writeCache:(String&)error // or nothing). So, we'll write to a temp file first, and rename the temp // file to the cache file only after we've finished writing the whole thing. - NSString *cachePathString = [m_cachePath path]; + NSString *cachePathString = m_cachePath.get().path; const char* cacheFileName = cachePathString.UTF8String; const char* tempFileName = [cachePathString stringByAppendingString:@".tmp"].UTF8String; int fd = open(cacheFileName, O_CREAT | O_WRONLY | O_EXLOCK | O_NONBLOCK, 0600); @@ -326,7 +326,7 @@ - (BOOL)writeCache:(String&)error }); JSC::BytecodeCacheError cacheError; - JSC::SourceCode sourceCode = [self sourceCode]; + JSC::SourceCode sourceCode = self.sourceCode; JSC::VM& vm = *toJS([m_virtualMachine JSContextGroupRef]); switch (m_type) { case kJSScriptTypeModule: diff --git a/Source/JavaScriptCore/API/JSScriptInternal.h b/Source/JavaScriptCore/API/JSScriptInternal.h index 951438d4232e..4e6764efe2df 100644 --- a/Source/JavaScriptCore/API/JSScriptInternal.h +++ b/Source/JavaScriptCore/API/JSScriptInternal.h @@ -44,11 +44,11 @@ class String; @interface JSScript(Internal) - (instancetype)init; -- (unsigned)hash; -- (const WTF::String&)source; -- (RefPtr)cachedBytecode; -- (JSC::JSSourceCode*)jsSourceCode; -- (JSC::SourceCode)sourceCode; +@property (nonatomic, readonly) unsigned hash; +@property (nonatomic, readonly) const WTF::String& source; +@property (nonatomic, readonly) RefPtr cachedBytecode; +@property (nonatomic, readonly) JSC::JSSourceCode *jsSourceCode; +@property (nonatomic, readonly) JSC::SourceCode sourceCode; - (BOOL)writeCache:(String&)error; @end diff --git a/Source/JavaScriptCore/API/JSScriptSourceProvider.mm b/Source/JavaScriptCore/API/JSScriptSourceProvider.mm index 56cee07e0e23..28c815dc72d8 100644 --- a/Source/JavaScriptCore/API/JSScriptSourceProvider.mm +++ b/Source/JavaScriptCore/API/JSScriptSourceProvider.mm @@ -33,17 +33,17 @@ unsigned JSScriptSourceProvider::hash() const { - return [m_script.get() hash]; + return m_script.get().hash; } StringView JSScriptSourceProvider::source() const { - return [m_script.get() source]; + return m_script.get().source; } RefPtr JSScriptSourceProvider::cachedBytecode() const { - return [m_script.get() cachedBytecode]; + return m_script.get().cachedBytecode; } #endif // JSC_OBJC_API_ENABLED diff --git a/Source/JavaScriptCore/API/JSValue.mm b/Source/JavaScriptCore/API/JSValue.mm index b916cc02d8d2..ca3161982b6b 100644 --- a/Source/JavaScriptCore/API/JSValue.mm +++ b/Source/JavaScriptCore/API/JSValue.mm @@ -74,7 +74,7 @@ @implementation JSValue { - (void)dealloc { if (_context) { - JSValueUnprotect([_context JSGlobalContextRef], m_value); + JSValueUnprotect(_context.JSGlobalContextRef, m_value); [_context release]; _context = nil; } @@ -83,7 +83,7 @@ - (void)dealloc - (NSString *)description { - if (id wrapped = tryUnwrapObjcObject([_context JSGlobalContextRef], m_value)) + if (id wrapped = tryUnwrapObjcObject(_context.JSGlobalContextRef, m_value)) return [wrapped description]; return [self toString]; } @@ -100,63 +100,63 @@ + (JSValue *)valueWithObject:(id)value inContext:(JSContext *)context + (JSValue *)valueWithBool:(BOOL)value inContext:(JSContext *)context { - return [JSValue valueWithJSValueRef:JSValueMakeBoolean([context JSGlobalContextRef], value) inContext:context]; + return [JSValue valueWithJSValueRef:JSValueMakeBoolean(context.JSGlobalContextRef, value) inContext:context]; } + (JSValue *)valueWithDouble:(double)value inContext:(JSContext *)context { - return [JSValue valueWithJSValueRef:JSValueMakeNumber([context JSGlobalContextRef], value) inContext:context]; + return [JSValue valueWithJSValueRef:JSValueMakeNumber(context.JSGlobalContextRef, value) inContext:context]; } + (JSValue *)valueWithInt32:(int32_t)value inContext:(JSContext *)context { - return [JSValue valueWithJSValueRef:JSValueMakeNumber([context JSGlobalContextRef], value) inContext:context]; + return [JSValue valueWithJSValueRef:JSValueMakeNumber(context.JSGlobalContextRef, value) inContext:context]; } + (JSValue *)valueWithUInt32:(uint32_t)value inContext:(JSContext *)context { - return [JSValue valueWithJSValueRef:JSValueMakeNumber([context JSGlobalContextRef], value) inContext:context]; + return [JSValue valueWithJSValueRef:JSValueMakeNumber(context.JSGlobalContextRef, value) inContext:context]; } + (JSValue *)valueWithNewObjectInContext:(JSContext *)context { - return [JSValue valueWithJSValueRef:JSObjectMake([context JSGlobalContextRef], 0, 0) inContext:context]; + return [JSValue valueWithJSValueRef:JSObjectMake(context.JSGlobalContextRef, 0, 0) inContext:context]; } + (JSValue *)valueWithNewArrayInContext:(JSContext *)context { - return [JSValue valueWithJSValueRef:JSObjectMakeArray([context JSGlobalContextRef], 0, NULL, 0) inContext:context]; + return [JSValue valueWithJSValueRef:JSObjectMakeArray(context.JSGlobalContextRef, 0, NULL, 0) inContext:context]; } + (JSValue *)valueWithNewRegularExpressionFromPattern:(NSString *)pattern flags:(NSString *)flags inContext:(JSContext *)context { auto patternString = OpaqueJSString::tryCreate(pattern); auto flagsString = OpaqueJSString::tryCreate(flags); - JSValueRef arguments[2] = { JSValueMakeString([context JSGlobalContextRef], patternString.get()), JSValueMakeString([context JSGlobalContextRef], flagsString.get()) }; - return [JSValue valueWithJSValueRef:JSObjectMakeRegExp([context JSGlobalContextRef], 2, arguments, 0) inContext:context]; + JSValueRef arguments[2] = { JSValueMakeString(context.JSGlobalContextRef, patternString.get()), JSValueMakeString(context.JSGlobalContextRef, flagsString.get()) }; + return [JSValue valueWithJSValueRef:JSObjectMakeRegExp(context.JSGlobalContextRef, 2, arguments, 0) inContext:context]; } + (JSValue *)valueWithNewErrorFromMessage:(NSString *)message inContext:(JSContext *)context { auto string = OpaqueJSString::tryCreate(message); - JSValueRef argument = JSValueMakeString([context JSGlobalContextRef], string.get()); - return [JSValue valueWithJSValueRef:JSObjectMakeError([context JSGlobalContextRef], 1, &argument, 0) inContext:context]; + JSValueRef argument = JSValueMakeString(context.JSGlobalContextRef, string.get()); + return [JSValue valueWithJSValueRef:JSObjectMakeError(context.JSGlobalContextRef, 1, &argument, 0) inContext:context]; } + (JSValue *)valueWithNullInContext:(JSContext *)context { - return [JSValue valueWithJSValueRef:JSValueMakeNull([context JSGlobalContextRef]) inContext:context]; + return [JSValue valueWithJSValueRef:JSValueMakeNull(context.JSGlobalContextRef) inContext:context]; } + (JSValue *)valueWithUndefinedInContext:(JSContext *)context { - return [JSValue valueWithJSValueRef:JSValueMakeUndefined([context JSGlobalContextRef]) inContext:context]; + return [JSValue valueWithJSValueRef:JSValueMakeUndefined(context.JSGlobalContextRef) inContext:context]; } + (JSValue *)valueWithNewSymbolFromDescription:(NSString *)description inContext:(JSContext *)context { auto string = OpaqueJSString::tryCreate(description); - return [JSValue valueWithJSValueRef:JSValueMakeSymbol([context JSGlobalContextRef], string.get()) inContext:context]; + return [JSValue valueWithJSValueRef:JSValueMakeSymbol(context.JSGlobalContextRef, string.get()) inContext:context]; } + (JSValue *)valueWithNewPromiseInContext:(JSContext *)context fromExecutor:(void (^)(JSValue *, JSValue *))executor @@ -164,7 +164,7 @@ + (JSValue *)valueWithNewPromiseInContext:(JSContext *)context fromExecutor:(voi JSObjectRef resolve; JSObjectRef reject; JSValueRef exception = nullptr; - JSObjectRef promise = JSObjectMakeDeferredPromise([context JSGlobalContextRef], &resolve, &reject, &exception); + JSObjectRef promise = JSObjectMakeDeferredPromise(context.JSGlobalContextRef, &resolve, &reject, &exception); if (exception) { [context notifyException:exception]; return [JSValue valueWithUndefinedInContext:context]; @@ -214,13 +214,13 @@ - (id)toObjectOfClass:(Class)expectedClass - (BOOL)toBool { - return JSValueToBoolean([_context JSGlobalContextRef], m_value); + return JSValueToBoolean(_context.JSGlobalContextRef, m_value); } - (double)toDouble { JSValueRef exception = 0; - double result = JSValueToNumber([_context JSGlobalContextRef], m_value, &exception); + double result = JSValueToNumber(_context.JSGlobalContextRef, m_value, &exception); if (exception) { [_context notifyException:exception]; return std::numeric_limits::quiet_NaN(); @@ -242,7 +242,7 @@ - (uint32_t)toUInt32 - (NSNumber *)toNumber { JSValueRef exception = 0; - id result = valueToNumber([_context JSGlobalContextRef], m_value, &exception); + id result = valueToNumber(_context.JSGlobalContextRef, m_value, &exception); if (exception) [_context notifyException:exception]; return result; @@ -251,7 +251,7 @@ - (NSNumber *)toNumber - (NSString *)toString { JSValueRef exception = 0; - id result = valueToString([_context JSGlobalContextRef], m_value, &exception); + id result = valueToString(_context.JSGlobalContextRef, m_value, &exception); if (exception) [_context notifyException:exception]; return result; @@ -260,7 +260,7 @@ - (NSString *)toString - (NSDate *)toDate { JSValueRef exception = 0; - id result = valueToDate([_context JSGlobalContextRef], m_value, &exception); + id result = valueToDate(_context.JSGlobalContextRef, m_value, &exception); if (exception) [_context notifyException:exception]; return result; @@ -269,7 +269,7 @@ - (NSDate *)toDate - (NSArray *)toArray { JSValueRef exception = 0; - id result = valueToArray([_context JSGlobalContextRef], m_value, &exception); + id result = valueToArray(_context.JSGlobalContextRef, m_value, &exception); if (exception) [_context notifyException:exception]; return result; @@ -278,7 +278,7 @@ - (NSArray *)toArray - (NSDictionary *)toDictionary { JSValueRef exception = 0; - id result = valueToDictionary([_context JSGlobalContextRef], m_value, &exception); + id result = valueToDictionary(_context.JSGlobalContextRef, m_value, &exception); if (exception) [_context notifyException:exception]; return result; @@ -287,9 +287,9 @@ - (NSDictionary *)toDictionary template inline Expected performPropertyOperation(NSStringFunction stringFunction, JSValueFunction jsFunction, JSValue* value, id propertyKey, Types... arguments) { - JSContext* context = [value context]; + JSContext *context = value.context; JSValueRef exception = nullptr; - JSObjectRef object = JSValueToObject([context JSGlobalContextRef], [value JSValueRef], &exception); + JSObjectRef object = JSValueToObject(context.JSGlobalContextRef, value.JSValueRef, &exception); if (exception) return Unexpected(exception); @@ -297,9 +297,9 @@ - (NSDictionary *)toDictionary // If it's a NSString already, reduce indirection and just pass the NSString. if ([propertyKey isKindOfClass:[NSString class]]) { auto name = OpaqueJSString::tryCreate((NSString *)propertyKey); - result = stringFunction([context JSGlobalContextRef], object, name.get(), arguments..., &exception); + result = stringFunction(context.JSGlobalContextRef, object, name.get(), arguments..., &exception); } else - result = jsFunction([context JSGlobalContextRef], object, [[JSValue valueWithObject:propertyKey inContext:context] JSValueRef], arguments..., &exception); + result = jsFunction(context.JSGlobalContextRef, object, [JSValue valueWithObject:propertyKey inContext:context].JSValueRef, arguments..., &exception); return Expected(result); } @@ -357,22 +357,25 @@ - (BOOL)hasProperty:(JSValueProperty)key - (void)defineProperty:(JSValueProperty)key descriptor:(id)descriptor { - [[_context globalObject][@"Object"] invokeMethod:@"defineProperty" withArguments:@[ self, key, descriptor ]]; + [_context.globalObject[@"Object"] invokeMethod:@"defineProperty" withArguments:@[ self, key, descriptor ]]; } - (JSValue *)valueAtIndex:(NSUInteger)index { // Properties that are higher than an unsigned value can hold are converted to a double then inserted as a normal property. // Indices that are bigger than the max allowed index size (UINT_MAX - 1) will be handled internally in get(). - if (index != (unsigned)index) + unsigned tempIndex = index; +#if CPU(ADDRESS64) + if (index != tempIndex) return [self valueForProperty:[[JSValue valueWithDouble:index inContext:_context] toString]]; +#endif JSValueRef exception = 0; - JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], m_value, &exception); + JSObjectRef object = JSValueToObject(_context.JSGlobalContextRef, m_value, &exception); if (exception) return [_context valueFromNotifyException:exception]; - JSValueRef result = JSObjectGetPropertyAtIndex([_context JSGlobalContextRef], object, (unsigned)index, &exception); + JSValueRef result = JSObjectGetPropertyAtIndex(_context.JSGlobalContextRef, object, tempIndex, &exception); if (exception) return [_context valueFromNotifyException:exception]; @@ -383,17 +386,20 @@ - (void)setValue:(id)value atIndex:(NSUInteger)index { // Properties that are higher than an unsigned value can hold are converted to a double, then inserted as a normal property. // Indices that are bigger than the max allowed index size (UINT_MAX - 1) will be handled internally in putByIndex(). - if (index != (unsigned)index) + unsigned tempIndex = index; +#if CPU(ADDRESS64) + if (index != tempIndex) return [self setValue:value forProperty:[[JSValue valueWithDouble:index inContext:_context] toString]]; +#endif JSValueRef exception = 0; - JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], m_value, &exception); + JSObjectRef object = JSValueToObject(_context.JSGlobalContextRef, m_value, &exception); if (exception) { [_context notifyException:exception]; return; } - JSObjectSetPropertyAtIndex([_context JSGlobalContextRef], object, (unsigned)index, objectToValue(_context, value), &exception); + JSObjectSetPropertyAtIndex(_context.JSGlobalContextRef, object, tempIndex, objectToValue(_context, value), &exception); if (exception) { [_context notifyException:exception]; return; @@ -465,23 +471,23 @@ - (BOOL)isSymbol - (BOOL)isArray { - return JSValueIsArray([_context JSGlobalContextRef], m_value); + return JSValueIsArray(_context.JSGlobalContextRef, m_value); } - (BOOL)isDate { - return JSValueIsDate([_context JSGlobalContextRef], m_value); + return JSValueIsDate(_context.JSGlobalContextRef, m_value); } - (BOOL)isEqualToObject:(id)value { - return JSValueIsStrictEqual([_context JSGlobalContextRef], m_value, objectToValue(_context, value)); + return JSValueIsStrictEqual(_context.JSGlobalContextRef, m_value, objectToValue(_context, value)); } - (BOOL)isEqualWithTypeCoercionToObject:(id)value { JSValueRef exception = 0; - BOOL result = JSValueIsEqual([_context JSGlobalContextRef], m_value, objectToValue(_context, value), &exception); + BOOL result = JSValueIsEqual(_context.JSGlobalContextRef, m_value, objectToValue(_context, value), &exception); if (exception) return [_context boolFromNotifyException:exception]; @@ -491,11 +497,11 @@ - (BOOL)isEqualWithTypeCoercionToObject:(id)value - (BOOL)isInstanceOf:(id)value { JSValueRef exception = 0; - JSObjectRef constructor = JSValueToObject([_context JSGlobalContextRef], objectToValue(_context, value), &exception); + JSObjectRef constructor = JSValueToObject(_context.JSGlobalContextRef, objectToValue(_context, value), &exception); if (exception) return [_context boolFromNotifyException:exception]; - BOOL result = JSValueIsInstanceOfConstructor([_context JSGlobalContextRef], m_value, constructor, &exception); + BOOL result = JSValueIsInstanceOfConstructor(_context.JSGlobalContextRef, m_value, constructor, &exception); if (exception) return [_context boolFromNotifyException:exception]; @@ -504,21 +510,21 @@ - (BOOL)isInstanceOf:(id)value - (JSValue *)callWithArguments:(NSArray *)argumentArray { - JSC::JSGlobalObject* globalObject = toJS([_context JSGlobalContextRef]); + JSC::JSGlobalObject* globalObject = toJS(_context.JSGlobalContextRef); JSC::VM& vm = globalObject->vm(); JSC::JSLockHolder locker(vm); - NSUInteger argumentCount = [argumentArray count]; - JSC::MarkedJSValueRefArray arguments([_context JSGlobalContextRef], argumentCount); - for (unsigned i = 0; i < argumentCount; ++i) - arguments[i] = objectToValue(_context, [argumentArray objectAtIndex:i]); + NSUInteger argumentCount = argumentArray.count; + JSC::MarkedJSValueRefArray arguments(_context.JSGlobalContextRef, argumentCount); + for (NSUInteger i = 0; i < argumentCount; ++i) + arguments[i] = objectToValue(_context, argumentArray[i]); JSValueRef exception = 0; - JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], m_value, &exception); + JSObjectRef object = JSValueToObject(_context.JSGlobalContextRef, m_value, &exception); if (exception) return [_context valueFromNotifyException:exception]; - JSValueRef result = JSObjectCallAsFunction([_context JSGlobalContextRef], object, 0, argumentCount, arguments.data(), &exception); + JSValueRef result = JSObjectCallAsFunction(_context.JSGlobalContextRef, object, 0, argumentCount, arguments.data(), &exception); if (exception) return [_context valueFromNotifyException:exception]; @@ -527,21 +533,21 @@ - (JSValue *)callWithArguments:(NSArray *)argumentArray - (JSValue *)constructWithArguments:(NSArray *)argumentArray { - JSC::JSGlobalObject* globalObject = toJS([_context JSGlobalContextRef]); + JSC::JSGlobalObject* globalObject = toJS(_context.JSGlobalContextRef); JSC::VM& vm = globalObject->vm(); JSC::JSLockHolder locker(vm); - NSUInteger argumentCount = [argumentArray count]; - JSC::MarkedJSValueRefArray arguments([_context JSGlobalContextRef], argumentCount); - for (unsigned i = 0; i < argumentCount; ++i) - arguments[i] = objectToValue(_context, [argumentArray objectAtIndex:i]); + NSUInteger argumentCount = argumentArray.count; + JSC::MarkedJSValueRefArray arguments(_context.JSGlobalContextRef, argumentCount); + for (NSUInteger i = 0; i < argumentCount; ++i) + arguments[i] = objectToValue(_context, argumentArray[i]); JSValueRef exception = 0; - JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], m_value, &exception); + JSObjectRef object = JSValueToObject(_context.JSGlobalContextRef, m_value, &exception); if (exception) return [_context valueFromNotifyException:exception]; - JSObjectRef result = JSObjectCallAsConstructor([_context JSGlobalContextRef], object, argumentCount, arguments.data(), &exception); + JSObjectRef result = JSObjectCallAsConstructor(_context.JSGlobalContextRef, object, argumentCount, arguments.data(), &exception); if (exception) return [_context valueFromNotifyException:exception]; @@ -550,30 +556,30 @@ - (JSValue *)constructWithArguments:(NSArray *)argumentArray - (JSValue *)invokeMethod:(NSString *)method withArguments:(NSArray *)arguments { - JSC::JSGlobalObject* globalObject = toJS([_context JSGlobalContextRef]); + JSC::JSGlobalObject* globalObject = toJS(_context.JSGlobalContextRef); JSC::VM& vm = globalObject->vm(); JSC::JSLockHolder locker(vm); - NSUInteger argumentCount = [arguments count]; - JSC::MarkedJSValueRefArray argumentArray([_context JSGlobalContextRef], argumentCount); - for (unsigned i = 0; i < argumentCount; ++i) - argumentArray[i] = objectToValue(_context, [arguments objectAtIndex:i]); + NSUInteger argumentCount = arguments.count; + JSC::MarkedJSValueRefArray argumentArray(_context.JSGlobalContextRef, argumentCount); + for (NSUInteger i = 0; i < argumentCount; ++i) + argumentArray[i] = objectToValue(_context, arguments[i]); JSValueRef exception = 0; - JSObjectRef thisObject = JSValueToObject([_context JSGlobalContextRef], m_value, &exception); + JSObjectRef thisObject = JSValueToObject(_context.JSGlobalContextRef, m_value, &exception); if (exception) return [_context valueFromNotifyException:exception]; auto name = OpaqueJSString::tryCreate(method); - JSValueRef function = JSObjectGetProperty([_context JSGlobalContextRef], thisObject, name.get(), &exception); + JSValueRef function = JSObjectGetProperty(_context.JSGlobalContextRef, thisObject, name.get(), &exception); if (exception) return [_context valueFromNotifyException:exception]; - JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], function, &exception); + JSObjectRef object = JSValueToObject(_context.JSGlobalContextRef, function, &exception); if (exception) return [_context valueFromNotifyException:exception]; - JSValueRef result = JSObjectCallAsFunction([_context JSGlobalContextRef], object, thisObject, argumentCount, argumentArray.data(), &exception); + JSValueRef result = JSObjectCallAsFunction(_context.JSGlobalContextRef, object, thisObject, argumentCount, argumentArray.data(), &exception); if (exception) return [_context valueFromNotifyException:exception]; @@ -776,7 +782,7 @@ static void reportExceptionToInspector(JSGlobalContextRef context, JSC::JSValue auto jsstring = adoptRef(JSValueToStringCopy(context, value, 0)); primitive = adoptCF(JSStringCopyCFString(kCFAllocatorDefault, jsstring.get())).bridgingAutorelease(); } else if (JSValueIsNull(context, value)) - primitive = [NSNull null]; + primitive = NSNull.null; else { ASSERT(JSValueIsUndefined(context, value)); primitive = nil; @@ -820,7 +826,7 @@ static id containerValueToObject(JSGlobalContextRef context, JSContainerConverto for (unsigned i = 0; i < length; ++i) { id objc = convertor.convert(JSObjectGetPropertyAtIndex(context, js, i, 0)); - [array addObject:objc ? objc : [NSNull null]]; + [array addObject:objc ? objc : NSNull.null]; } } else { ASSERT([current.objc isKindOfClass:[NSMutableDictionary class]]); @@ -847,10 +853,10 @@ static id containerValueToObject(JSGlobalContextRef context, JSContainerConverto id valueToObject(JSContext *context, JSValueRef value) { - JSContainerConvertor::Task result = valueToObjectWithoutCopy([context JSGlobalContextRef], value); + JSContainerConvertor::Task result = valueToObjectWithoutCopy(context.JSGlobalContextRef, value); if (result.type == ContainerNone) return result.objc; - return containerValueToObject([context JSGlobalContextRef], result); + return containerValueToObject(context.JSGlobalContextRef, result); } id valueToNumber(JSGlobalContextRef context, JSValueRef value, JSValueRef* exception) @@ -1006,7 +1012,7 @@ inline bool isNSBoolean(id object) static ObjcContainerConvertor::Task objectToValueWithoutCopy(JSContext *context, id object) { - JSGlobalContextRef contextRef = audit([context JSGlobalContextRef]); + JSGlobalContextRef contextRef = audit(context.JSGlobalContextRef); if (!object) return { object, JSValueMakeUndefined(contextRef), ContainerNone }; @@ -1042,7 +1048,7 @@ inline bool isNSBoolean(id object) } if ([object isKindOfClass:[JSManagedValue class]]) { - JSValue *value = [static_cast(object) value]; + JSValue *value = static_cast(object).value; if (!value) return { object, JSValueMakeUndefined(contextRef), ContainerNone }; return { object, value->m_value, ContainerNone }; @@ -1054,7 +1060,7 @@ inline bool isNSBoolean(id object) JSValueRef objectToValue(JSContext *context, id object) { - JSGlobalContextRef contextRef = [context JSGlobalContextRef]; + JSGlobalContextRef contextRef = context.JSGlobalContextRef; ObjcContainerConvertor::Task task = objectToValueWithoutCopy(context, object); if (task.type == ContainerNone) @@ -1073,9 +1079,9 @@ JSValueRef objectToValue(JSContext *context, id object) if (current.type == ContainerArray) { ASSERT([current.objc isKindOfClass:[NSArray class]]); NSArray *array = (NSArray *)current.objc; - NSUInteger count = [array count]; + NSUInteger count = array.count; for (NSUInteger index = 0; index < count; ++index) - JSObjectSetPropertyAtIndex(contextRef, js, index, convertor.convert([array objectAtIndex:index]), 0); + JSObjectSetPropertyAtIndex(contextRef, js, index, convertor.convert(array[index]), 0); } else { ASSERT(current.type == ContainerDictionary); ASSERT([current.objc isKindOfClass:[NSDictionary class]]); @@ -1083,7 +1089,7 @@ JSValueRef objectToValue(JSContext *context, id object) for (id key in [dictionary keyEnumerator]) { if ([key isKindOfClass:[NSString class]]) { auto propertyName = OpaqueJSString::tryCreate((NSString *)key); - JSObjectSetProperty(contextRef, js, propertyName.get(), convertor.convert([dictionary objectForKey:key]), 0, 0); + JSObjectSetProperty(contextRef, js, propertyName.get(), convertor.convert(dictionary[key]), 0, 0); } } } @@ -1120,7 +1126,7 @@ - (JSValue *)initWithValue:(JSValueRef)value inContext:(JSContext *)context _context = [context retain]; m_value = value; - JSValueProtect([_context JSGlobalContextRef], m_value); + JSValueProtect(_context.JSGlobalContextRef, m_value); return self; } @@ -1242,7 +1248,7 @@ + (SEL)selectorForValueToStruct:(const char *)structTag const char* methodTypes = method_getTypeEncoding(class_getClassMethod([JSValue class], selector)); NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:methodTypes]]; - [invocation setSelector:selector]; + invocation.selector = selector; return invocation; } @@ -1254,7 +1260,7 @@ + (SEL)selectorForValueToStruct:(const char *)structTag const char* methodTypes = method_getTypeEncoding(class_getInstanceMethod([JSValue class], selector)); NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:methodTypes]]; - [invocation setSelector:selector]; + invocation.selector = selector; return invocation; } diff --git a/Source/JavaScriptCore/API/JSVirtualMachine.mm b/Source/JavaScriptCore/API/JSVirtualMachine.mm index 1bc23e443805..03cd7dc720e0 100644 --- a/Source/JavaScriptCore/API/JSVirtualMachine.mm +++ b/Source/JavaScriptCore/API/JSVirtualMachine.mm @@ -131,10 +131,10 @@ - (void)dealloc static id getInternalObjcObject(id object) { if ([object isKindOfClass:[JSManagedValue class]]) { - JSValue* value = [static_cast(object) value]; + JSValue *value = (static_cast(object)).value; if (!value) return nil; - id temp = tryUnwrapObjcObject([value.context JSGlobalContextRef], [value JSValueRef]); + id temp = tryUnwrapObjcObject(value.context.JSGlobalContextRef, value.JSValueRef); if (temp) return temp; return object; @@ -142,7 +142,7 @@ static id getInternalObjcObject(id object) if ([object isKindOfClass:[JSValue class]]) { JSValue *value = static_cast(object); - object = tryUnwrapObjcObject([value.context JSGlobalContextRef], [value JSValueRef]); + object = tryUnwrapObjcObject(value.context.JSGlobalContextRef, value.JSValueRef); } return object; @@ -220,7 +220,7 @@ - (void)removeManagedReference:(id)object withOwner:(id)owner if (count == 1) NSMapRemove(ownedObjects, (__bridge void*)object); - if (![ownedObjects count]) { + if (!ownedObjects.count) { [m_externalObjectGraph removeObjectForKey:owner]; [m_externalRememberedSet removeObjectForKey:owner]; } diff --git a/Source/JavaScriptCore/API/JSWrapperMap.mm b/Source/JavaScriptCore/API/JSWrapperMap.mm index 88140b983b40..781ff9434c00 100644 --- a/Source/JavaScriptCore/API/JSWrapperMap.mm +++ b/Source/JavaScriptCore/API/JSWrapperMap.mm @@ -69,7 +69,7 @@ - (JSObjCClassInfo*)classInfoForClass:(Class)cls; // Use 'index' to check for colons, if there are none, this is easy! const char* firstColon = strchr(start, ':'); if (!firstColon) - return [NSString stringWithUTF8String:start]; + return @(start); // 'header' is the length of string up to the first colon. size_t header = firstColon - start; @@ -101,7 +101,7 @@ - (JSObjCClassInfo*)classInfoForClass:(Class)cls; // If we get here, we've consumed a ':' - wash, rinse, repeat. } done: - return [NSString stringWithUTF8String:buffer.data()]; + return @(buffer.data()); } static bool constructorHasInstance(JSContextRef ctx, JSObjectRef constructorRef, JSValueRef possibleInstance, JSValueRef*) @@ -137,9 +137,9 @@ static bool constructorHasInstance(JSContextRef ctx, JSObjectRef constructorRef, { JSClassDefinition definition; definition = kJSClassDefinitionEmpty; - definition.className = [brand UTF8String]; + definition.className = brand.UTF8String; JSClassRef classRef = JSClassCreate(&definition); - JSC::JSObject* result = makeWrapper([context JSGlobalContextRef], classRef, cls); + JSC::JSObject* result = makeWrapper(context.JSGlobalContextRef, classRef, cls); JSClassRelease(classRef); return result; } @@ -148,10 +148,10 @@ static bool constructorHasInstance(JSContextRef ctx, JSObjectRef constructorRef, { JSClassDefinition definition; definition = kJSClassDefinitionEmpty; - definition.className = [brand UTF8String]; + definition.className = brand.UTF8String; definition.hasInstance = constructorHasInstance; JSClassRef classRef = JSClassCreate(&definition); - JSC::JSObject* result = makeWrapper([context JSGlobalContextRef], classRef, cls); + JSC::JSObject* result = makeWrapper(context.JSGlobalContextRef, classRef, cls); JSClassRelease(classRef); return result; } @@ -160,7 +160,7 @@ static bool constructorHasInstance(JSContextRef ctx, JSObjectRef constructorRef, // name mapping, separated by a __JS_EXPORT_AS__ delimiter. static RetainPtr createRenameMap(Protocol *protocol, BOOL isInstanceMethod) { - auto renameMap = adoptNS([[NSMutableDictionary alloc] init]); + NSMutableDictionary *renameMap = [[NSMutableDictionary alloc] init]; forEachMethodInProtocol(protocol, NO, isInstanceMethod, ^(SEL sel, const char*){ NSString *rename = @(sel_getName(sel)); @@ -169,30 +169,30 @@ static bool constructorHasInstance(JSContextRef ctx, JSObjectRef constructorRef, return; NSString *selector = [rename substringToIndex:range.location]; NSUInteger begin = range.location + range.length; - NSUInteger length = [rename length] - begin - 1; + NSUInteger length = rename.length - begin - 1; NSString *name = [rename substringWithRange:(NSRange){ begin, length }]; - renameMap.get()[selector] = name; + renameMap[selector] = name; }); - return renameMap; + return adoptNS(renameMap); } inline void putNonEnumerable(JSContext *context, JSValue *base, NSString *propertyName, JSValue *value) { - if (![base isObject]) + if (!base.isObject) return; - JSC::JSGlobalObject* globalObject = toJS([context JSGlobalContextRef]); + JSC::JSGlobalObject* globalObject = toJS(context.JSGlobalContextRef); JSC::VM& vm = globalObject->vm(); JSC::JSLockHolder locker(vm); auto scope = DECLARE_CATCH_SCOPE(vm); - JSC::JSObject* baseObject = JSC::asObject(toJS(globalObject, [base JSValueRef])); + JSC::JSObject* baseObject = JSC::asObject(toJS(globalObject, base.JSValueRef)); auto name = OpaqueJSString::tryCreate(propertyName); if (!name) return; JSC::PropertyDescriptor descriptor; - descriptor.setValue(toJS(globalObject, [value JSValueRef])); + descriptor.setValue(toJS(globalObject, value.JSValueRef)); descriptor.setEnumerable(false); descriptor.setConfigurable(true); descriptor.setWritable(true); @@ -200,7 +200,7 @@ inline void putNonEnumerable(JSContext *context, JSValue *base, NSString *proper baseObject->methodTable()->defineOwnProperty(baseObject, globalObject, name->identifier(&vm), descriptor, shouldThrow); JSValueRef exception = 0; - if (handleExceptionIfNeeded(scope, [context JSGlobalContextRef], &exception) == ExceptionStatus::DidThrow) + if (handleExceptionIfNeeded(scope, context.JSGlobalContextRef, &exception) == ExceptionStatus::DidThrow) [context valueFromNotifyException:exception]; } @@ -209,7 +209,7 @@ static bool isInitFamilyMethod(NSString *name) NSUInteger i = 0; // Skip over initial underscores. - for (; i < [name length]; ++i) { + for (; i < name.length; ++i) { if ([name characterAtIndex:i] != '_') break; } @@ -217,17 +217,17 @@ static bool isInitFamilyMethod(NSString *name) // Match 'init'. NSUInteger initIndex = 0; NSString* init = @"init"; - for (; i < [name length] && initIndex < [init length]; ++i, ++initIndex) { + for (; i < name.length && initIndex < init.length; ++i, ++initIndex) { if ([name characterAtIndex:i] != [init characterAtIndex:initIndex]) return false; } // We didn't match all of 'init'. - if (initIndex < [init length]) + if (initIndex < init.length) return false; // If we're at the end or the next character is a capital letter then this is an init-family selector. - return i == [name length] || [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[name characterAtIndex:i]]; + return i == name.length || [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[name characterAtIndex:i]]; } static bool shouldSkipMethodWithName(NSString *name) @@ -266,16 +266,16 @@ static void copyMethodsToObject(JSContext *context, Class objcClass, Protocol *p name = renameMap.get()[name]; if (!name) name = selectorToPropertyName(nameCStr); - JSC::JSGlobalObject* globalObject = toJS([context JSGlobalContextRef]); + JSC::JSGlobalObject* globalObject = toJS(context.JSGlobalContextRef); JSValue *existingMethod = object[name]; // ObjCCallbackFunction does a dynamic lookup for the // selector before calling the method. In order to save - // memory we only put one callback object in any givin + // memory we only put one callback object in any given // prototype chain. However, to handle the client trying // to override normal builtins e.g. "toString" we check if // the existing value on the prototype chain is an ObjC // callback already. - if ([existingMethod isObject] && JSC::jsDynamicCast(toJS(globalObject, [existingMethod JSValueRef]))) + if (existingMethod.isObject && JSC::jsDynamicCast(toJS(globalObject, existingMethod.JSValueRef))) return; JSObjectRef method = objCCallbackFunctionForMethod(context, objcClass, protocol, isInstanceMethod, sel, types); if (method) @@ -346,7 +346,7 @@ static void copyPrototypeProperties(JSContext *context, Class objcClass, Protoco Property property { name, nullptr, nullptr }; bool readonly = parsePropertyAttributes(objcProperty, property); - // Add the names of the getter & setter methods to + // Add the names of the getter & setter methods if (!property.getterName) property.getterName = @(name); accessorMethods[property.getterName.get()] = undefined; @@ -393,9 +393,9 @@ @interface JSObjCClassInfo : NSObject { } - (instancetype)initForClass:(Class)cls; -- (JSC::JSObject *)wrapperForObject:(id)object inContext:(JSContext *)context; -- (JSC::JSObject *)constructorInContext:(JSContext *)context; -- (JSC::JSObject *)prototypeInContext:(JSContext *)context; +- (JSC::JSObject *)wrapperForObject:(id)object inContext:(JSContext *)context NS_RETURNS_INNER_POINTER; +- (JSC::JSObject *)constructorInContext:(JSContext *)context NS_RETURNS_INNER_POINTER; +- (JSC::JSObject *)prototypeInContext:(JSContext *)context NS_RETURNS_INNER_POINTER; @end @@ -489,7 +489,7 @@ - (ConstructorPrototypePair)allocateConstructorAndPrototypeInContext:(JSContext JSC::JSObject* jsConstructor = m_constructor.get(); if (!superClassInfo) { - JSC::JSGlobalObject* globalObject = toJSGlobalObject([context JSGlobalContextRef]); + JSC::JSGlobalObject* globalObject = toJSGlobalObject(context.JSGlobalContextRef); if (!jsConstructor) jsConstructor = globalObject->objectConstructor(); @@ -519,7 +519,7 @@ - (ConstructorPrototypePair)allocateConstructorAndPrototypeInContext:(JSContext // Set [Prototype]. JSC::JSObject* superClassPrototype = [superClassInfo prototypeInContext:context]; - JSObjectSetPrototype([context JSGlobalContextRef], toRef(jsPrototype), toRef(superClassPrototype)); + JSObjectSetPrototype(context.JSGlobalContextRef, toRef(jsPrototype), toRef(superClassPrototype)); } m_prototype = jsPrototype; @@ -543,7 +543,7 @@ - (ConstructorPrototypePair)allocateConstructorAndPrototypeInContext:(JSContext JSC::Structure* structure = [self structureInContext:context]; - JSC::JSGlobalObject* globalObject = toJS([context JSGlobalContextRef]); + JSC::JSGlobalObject* globalObject = toJS(context.JSGlobalContextRef); JSC::VM& vm = globalObject->vm(); JSC::JSLockHolder locker(vm); @@ -576,7 +576,7 @@ - (ConstructorPrototypePair)allocateConstructorAndPrototypeInContext:(JSContext if (structure) return structure; - JSC::JSGlobalObject* globalObject = toJSGlobalObject([context JSGlobalContextRef]); + JSC::JSGlobalObject* globalObject = toJSGlobalObject(context.JSGlobalContextRef); JSC::JSObject* prototype = [self prototypeInContext:context]; m_structure = JSC::JSCallbackObject::createStructure(globalObject->vm(), globalObject, prototype); diff --git a/Source/JavaScriptCore/API/ObjCCallbackFunction.mm b/Source/JavaScriptCore/API/ObjCCallbackFunction.mm index 9ddd0d94a29e..e5460f6ba28f 100644 --- a/Source/JavaScriptCore/API/ObjCCallbackFunction.mm +++ b/Source/JavaScriptCore/API/ObjCCallbackFunction.mm @@ -58,7 +58,7 @@ class CallbackArgumentBoolean final : public CallbackArgument { void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef*) final { - bool value = JSValueToBoolean([context JSGlobalContextRef], argument); + bool value = JSValueToBoolean(context.JSGlobalContextRef, argument); [invocation setArgument:&value atIndex:argumentNumber]; } }; @@ -68,7 +68,7 @@ void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) final { ASSERT(exception && !*exception); - T value = (T)JSC::toInt32(JSValueToNumber([context JSGlobalContextRef], argument, exception)); + T value = (T)JSC::toInt32(JSValueToNumber(context.JSGlobalContextRef, argument, exception)); if (*exception) return; [invocation setArgument:&value atIndex:argumentNumber]; @@ -80,7 +80,7 @@ void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) final { ASSERT(exception && !*exception); - T value = (T)JSValueToNumber([context JSGlobalContextRef], argument, exception); + T value = (T)JSValueToNumber(context.JSGlobalContextRef, argument, exception); if (*exception) return; [invocation setArgument:&value atIndex:argumentNumber]; @@ -114,7 +114,7 @@ void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) final { ASSERT(exception && !*exception); - JSGlobalContextRef contextRef = [context JSGlobalContextRef]; + JSGlobalContextRef contextRef = context.JSGlobalContextRef; id object = tryUnwrapObjcObject(contextRef, argument); if (object && [object isKindOfClass:m_class.get()]) { @@ -138,7 +138,7 @@ void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) final { ASSERT(exception && !*exception); - id value = valueToNumber([context JSGlobalContextRef], argument, exception); + id value = valueToNumber(context.JSGlobalContextRef, argument, exception); if (*exception) return; [invocation setArgument:&value atIndex:argumentNumber]; @@ -149,7 +149,7 @@ void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) final { ASSERT(exception && !*exception); - id value = valueToString([context JSGlobalContextRef], argument, exception); + id value = valueToString(context.JSGlobalContextRef, argument, exception); if (*exception) return; [invocation setArgument:&value atIndex:argumentNumber]; @@ -160,7 +160,7 @@ void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) final { ASSERT(exception && !*exception); - id value = valueToDate([context JSGlobalContextRef], argument, exception); + id value = valueToDate(context.JSGlobalContextRef, argument, exception); if (*exception) return; [invocation setArgument:&value atIndex:argumentNumber]; @@ -171,7 +171,7 @@ void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) final { ASSERT(exception && !*exception); - id value = valueToArray([context JSGlobalContextRef], argument, exception); + id value = valueToArray(context.JSGlobalContextRef, argument, exception); if (*exception) return; [invocation setArgument:&value atIndex:argumentNumber]; @@ -182,7 +182,7 @@ void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) final { ASSERT(exception && !*exception); - id value = valueToDictionary([context JSGlobalContextRef], argument, exception); + id value = valueToDictionary(context.JSGlobalContextRef, argument, exception); if (*exception) return; [invocation setArgument:&value atIndex:argumentNumber]; @@ -292,7 +292,7 @@ static ResultType typeStruct(const char* begin, const char* end) class CallbackResultVoid final : public CallbackResult { JSValueRef get(NSInvocation *, JSContext *context, JSValueRef*) final { - return JSValueMakeUndefined([context JSGlobalContextRef]); + return JSValueMakeUndefined(context.JSGlobalContextRef); } }; @@ -311,7 +311,7 @@ JSValueRef get(NSInvocation *invocation, JSContext *context, JSValueRef*) final { T value; [invocation getReturnValue:&value]; - return JSValueMakeNumber([context JSGlobalContextRef], value); + return JSValueMakeNumber(context.JSGlobalContextRef, value); } }; @@ -320,7 +320,7 @@ JSValueRef get(NSInvocation *invocation, JSContext *context, JSValueRef*) final { bool value; [invocation getReturnValue:&value]; - return JSValueMakeBoolean([context JSGlobalContextRef], value); + return JSValueMakeBoolean(context.JSGlobalContextRef, value); } }; @@ -427,7 +427,7 @@ void destroy(Heap& heap) // We need to explicitly release the target since we didn't call // -retainArguments on m_invocation (and we don't want to do so). if (m_type == CallbackBlock || m_type == CallbackClassMethod) - heap.releaseSoon(adoptNS([m_invocation.get() target])); + heap.releaseSoon(adoptNS(m_invocation.get().target)); m_instanceClass = nil; } @@ -435,14 +435,14 @@ void destroy(Heap& heap) id wrappedBlock() { - return m_type == CallbackBlock ? [m_invocation target] : nil; + return m_type == CallbackBlock ? m_invocation.get().target : nil; } id wrappedConstructor() { switch (m_type) { case CallbackBlock: - return [m_invocation target]; + return m_invocation.get().target; case CallbackInitMethod: return m_instanceClass.get(); default: @@ -482,7 +482,7 @@ static JSValueRef objCCallbackFunctionCallAsFunction(JSContextRef callerContext, JSContext *context = [JSContext contextWithJSGlobalContextRef:toGlobalRef(callback->globalObject())]; if (impl->type() == CallbackInitMethod) { - JSGlobalContextRef contextRef = [context JSGlobalContextRef]; + JSGlobalContextRef contextRef = context.JSGlobalContextRef; *exception = toRef(JSC::createTypeError(toJS(contextRef), "Cannot call a class constructor without |new|"_s)); if (*exception) return nullptr; @@ -524,7 +524,7 @@ static JSObjectRef objCCallbackFunctionCallAsConstructor(JSContextRef callerCont if (*exception) return nullptr; - JSGlobalContextRef contextRef = [context JSGlobalContextRef]; + JSGlobalContextRef contextRef = context.JSGlobalContextRef; if (!JSValueIsObject(contextRef, result)) { *exception = toRef(JSC::createTypeError(toJS(contextRef), "Objective-C blocks called as constructors must return an object."_s)); return nullptr; @@ -583,7 +583,7 @@ static JSObjectRef objCCallbackFunctionCallAsConstructor(JSContextRef callerCont JSValueRef ObjCCallbackFunctionImpl::call(JSContext *context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { ASSERT(exception && !*exception); - JSGlobalContextRef contextRef = [context JSGlobalContextRef]; + JSGlobalContextRef contextRef = context.JSGlobalContextRef; id target; size_t firstArgument; @@ -597,7 +597,7 @@ static JSObjectRef objCCallbackFunctionCallAsConstructor(JSContextRef callerCont return nullptr; return JSValueMakeUndefined(contextRef); } - [m_invocation setTarget:target]; + m_invocation.get().target = target; firstArgument = 2; break; } @@ -609,7 +609,7 @@ static JSObjectRef objCCallbackFunctionCallAsConstructor(JSContextRef callerCont return nullptr; return JSValueMakeUndefined(contextRef); } - [m_invocation setTarget:target]; + m_invocation.get().target = target; firstArgument = 2; break; } @@ -697,7 +697,6 @@ static JSObjectRef objCCallbackFunctionForInvocation(JSContext *context, NSInvoc std::unique_ptr arguments; auto* nextArgument = &arguments; - unsigned argumentCount = 0; while (*position) { auto argument = parseObjCType(position); if (!argument || !skipNumber(position)) @@ -705,10 +704,9 @@ static JSObjectRef objCCallbackFunctionForInvocation(JSContext *context, NSInvoc *nextArgument = WTFMove(argument); nextArgument = &(*nextArgument)->m_next; - ++argumentCount; } - JSC::JSGlobalObject* globalObject = toJS([context JSGlobalContextRef]); + JSC::JSGlobalObject* globalObject = toJS(context.JSGlobalContextRef); JSC::VM& vm = globalObject->vm(); JSC::JSLockHolder locker(vm); auto impl = makeUnique(invocation, type, instanceClass, WTFMove(arguments), WTFMove(result)); @@ -719,16 +717,17 @@ static JSObjectRef objCCallbackFunctionForInvocation(JSContext *context, NSInvoc JSObjectRef objCCallbackFunctionForInit(JSContext *context, Class cls, Protocol *protocol, SEL sel, const char* types) { NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:types]]; - [invocation setSelector:sel]; + invocation.selector = sel; return objCCallbackFunctionForInvocation(context, invocation, CallbackInitMethod, cls, _protocol_getMethodTypeEncoding(protocol, sel, YES, YES)); } JSObjectRef objCCallbackFunctionForMethod(JSContext *context, Class cls, Protocol *protocol, BOOL isInstanceMethod, SEL sel, const char* types) { NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:types]]; - [invocation setSelector:sel]; + invocation.selector = sel; + if (!isInstanceMethod) { - [invocation setTarget:cls]; + invocation.target = cls; // We need to retain the target Class because m_invocation doesn't retain it by default (and we don't want it to). // FIXME: What releases it? CFRetain((__bridge CFTypeRef)cls); @@ -747,7 +746,7 @@ JSObjectRef objCCallbackFunctionForBlock(JSContext *context, id target) // would be retained indefinitely between invocations of the callback. // Additionally, we copy the target because we want the block to stick around // until the ObjCCallbackFunctionImpl is destroyed. - [invocation setTarget:[target copy]]; + invocation.target = [target copy]; return objCCallbackFunctionForInvocation(context, invocation, CallbackBlock, nil, signature); } diff --git a/Source/JavaScriptCore/API/tests/CurrentThisInsideBlockGetterTest.mm b/Source/JavaScriptCore/API/tests/CurrentThisInsideBlockGetterTest.mm index 0d917472f7c0..a906d8b4c90a 100644 --- a/Source/JavaScriptCore/API/tests/CurrentThisInsideBlockGetterTest.mm +++ b/Source/JavaScriptCore/API/tests/CurrentThisInsideBlockGetterTest.mm @@ -82,7 +82,7 @@ @implementation JSValue (ConstructorCreation) + (JSValue *)valueWithConstructorDescriptor:(id)constructorDescriptor inContext:(JSContext *)context { NSMutableDictionary *privateProperties = [@{ @"constructorDescriptor" : constructorDescriptor } mutableCopy]; - JSGlobalContextRef ctx = [context JSGlobalContextRef]; + JSGlobalContextRef ctx = context.JSGlobalContextRef; JSObjectRef constructorRef = JSObjectMake(ctx, ConstructorClass(), const_cast(CFBridgingRetain(privateProperties))); JSValue *constructor = [JSValue valueWithJSValueRef:constructorRef inContext:context]; return constructor; diff --git a/Source/JavaScriptCore/API/tests/DateTests.mm b/Source/JavaScriptCore/API/tests/DateTests.mm index 6652177de417..d15d237657db 100644 --- a/Source/JavaScriptCore/API/tests/DateTests.mm +++ b/Source/JavaScriptCore/API/tests/DateTests.mm @@ -55,20 +55,20 @@ + (void) NSDateToJSDateTest int minute = [[jsNow invokeMethod:@"getMinutes" withArguments:@[]] toInt32]; int second = [[jsNow invokeMethod:@"getSeconds" withArguments:@[]] toInt32]; - checkResult(@"NSDate to JS Date", year == [components year] - && month == [components month] - && day == [components day] - && hour == [components hour] - && minute == [components minute] - && second == [components second]); + checkResult(@"NSDate to JS Date", year == components.year + && month == components.month + && day == components.day + && hour == components.hour + && minute == components.minute + && second == components.second); } + (void) JSDateToNSDateTest { JSContext *context = [[JSContext alloc] init]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; - [formatter setDateFormat:@"MMMM dd',' yyyy hh:mm:ss"]; - [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; + formatter.dateFormat = @"MMMM dd',' yyyy hh:mm:ss"; + formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; NSDate *februaryFourth2014 = [formatter dateFromString:@"February 4, 2014 11:40:03"]; NSDateComponents *components = [[NSCalendar currentCalendar] components:unitFlags fromDate:februaryFourth2014]; // Months are 0-indexed for JavaScript Dates. @@ -81,12 +81,12 @@ + (void) JSDateToNSDateTest int minute = [[jsDate invokeMethod:@"getMinutes" withArguments:@[]] toInt32]; int second = [[jsDate invokeMethod:@"getSeconds" withArguments:@[]] toInt32]; - checkResult(@"JS Date to NSDate", year == [components year] - && month == [components month] - && day == [components day] - && hour == [components hour] - && minute == [components minute] - && second == [components second]); + checkResult(@"JS Date to NSDate", year == components.year + && month == components.month + && day == components.day + && hour == components.hour + && minute == components.minute + && second == components.second); } + (void) roundTripThroughJSDateTest @@ -94,8 +94,8 @@ + (void) roundTripThroughJSDateTest JSContext *context = [[JSContext alloc] init]; [context evaluateScript:@"function jsReturnDate(date) { return date; }"]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; - [formatter setDateFormat:@"MMMM dd',' yyyy hh:mm:ss"]; - [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; + formatter.dateFormat = @"MMMM dd',' yyyy hh:mm:ss"; + formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; NSDate *februaryFourth2014 = [formatter dateFromString:@"February 4, 2014 11:40:03"]; NSDateComponents *components = [[NSCalendar currentCalendar] components:unitFlags fromDate:februaryFourth2014]; @@ -108,12 +108,12 @@ + (void) roundTripThroughJSDateTest int minute = [[roundTripThroughJS invokeMethod:@"getMinutes" withArguments:@[]] toInt32]; int second = [[roundTripThroughJS invokeMethod:@"getSeconds" withArguments:@[]] toInt32]; - checkResult(@"JS date round trip", year == [components year] - && month == [components month] - && day == [components day] - && hour == [components hour] - && minute == [components minute] - && second == [components second]); + checkResult(@"JS date round trip", year == components.year + && month == components.month + && day == components.day + && hour == components.hour + && minute == components.minute + && second == components.second); } + (void) roundTripThroughObjCDateTest @@ -134,7 +134,7 @@ + (void) roundTripThroughObjCDateTest && date.getMilliseconds() === result.getMilliseconds();\ }"]; - checkResult(@"ObjC date round trip", [[context[@"test"] callWithArguments:@[]] toBool]); + checkResult(@"ObjC date round trip", [context[@"test"] callWithArguments:@[]].toBool); } @end diff --git a/Source/JavaScriptCore/API/tests/Regress141275.mm b/Source/JavaScriptCore/API/tests/Regress141275.mm index e9a14b45d493..5eb4b6345360 100644 --- a/Source/JavaScriptCore/API/tests/Regress141275.mm +++ b/Source/JavaScriptCore/API/tests/Regress141275.mm @@ -115,7 +115,7 @@ - (instancetype)init __pendingTasks = [NSMutableArray new]; NSThread* jsThread = [[NSThread alloc] initWithTarget:self selector:@selector(_jsThreadMain) object:nil]; - [jsThread setName:@"JSTEval"]; + jsThread.name = @"JSTEval"; [jsThread start]; } @@ -182,14 +182,14 @@ - (void)waitForTasksDoneAndReportResults NSString* passFailString = @"PASSED"; if (!dispatch_semaphore_wait(_allScriptsDone, dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC))) { - int totalScriptsRun = [_jsContext[@"counter"] toInt32]; + uint32_t totalScriptsRun = [_jsContext[@"counter"] toUInt32]; if (totalScriptsRun != scriptToEvaluate) { passFailString = @"FAILED"; failed = 1; } - NSLog(@" Ran a total of %d scripts: %@", totalScriptsRun, passFailString); + NSLog(@" Ran a total of %u scripts: %@", totalScriptsRun, passFailString); } else { passFailString = @"FAILED"; failed = 1; @@ -241,7 +241,7 @@ - (void)_jsThreadMain CFRunLoopRun(); @synchronized(self) { - NSMutableDictionary* threadDict = [[NSThread currentThread] threadDictionary]; + NSMutableDictionary *threadDict = NSThread.currentThread.threadDictionary; [threadDict removeObjectForKey:threadDict[JSTEvaluatorThreadContextKey]]; CFRelease(_jsThreadRunLoopSource); @@ -268,7 +268,7 @@ - (void)_sourceScheduledOnRunLoop:(CFRunLoopRef)runLoop - (void)_setupEvaluatorThreadContextIfNeeded { - NSMutableDictionary* threadDict = [[NSThread currentThread] threadDictionary]; + NSMutableDictionary *threadDict = NSThread.currentThread.threadDictionary; JSTEvaluatorThreadContext* context = threadDict[JSTEvaluatorThreadContextKey]; // The evaluator may be other evualuator, or nil if this thread has not been used before. Eaither way take ownership. if (context.evaluator != self) { @@ -322,7 +322,7 @@ - (void)_sourcePerform } dispatch_barrier_sync(_jsSourcePerformQueue, ^{ - if ([self->_jsContext[@"counter"] toInt32] == scriptToEvaluate) + if ([self->_jsContext[@"counter"] toUInt32] == scriptToEvaluate) dispatch_semaphore_signal(self->_allScriptsDone); }); } @@ -331,7 +331,7 @@ - (void)_sourcePerform - (void)_sourceCanceledOnRunLoop:(CFRunLoopRef)runLoop { UNUSED_PARAM(runLoop); - assert([[[NSThread currentThread] name] isEqualToString:@"JSTEval"]); + assert([NSThread.currentThread.name isEqualToString:@"JSTEval"]); @synchronized(self) { assert(_jsThreadRunLoop); @@ -362,7 +362,7 @@ void runRegress141275() }; [evaluator evaluateBlock:^(JSContext* context) { - JSSynchronousGarbageCollectForDebugging([context JSGlobalContextRef]); + JSSynchronousGarbageCollectForDebugging(context.JSGlobalContextRef); } completion:showErrorIfNeeded]; [evaluator evaluateBlock:^(JSContext* context) { @@ -375,7 +375,7 @@ void runRegress141275() NSLog(@"Error: %@", error); }); } - for (unsigned i = 0; i < scriptToEvaluate; i++) + for (NSUInteger i = 0; i < scriptToEvaluate; i++) [evaluator evaluateScript:@"this['counter']++; this['wait']();" completion:showErrorIfNeeded]; }]; diff --git a/Source/JavaScriptCore/API/tests/Regress141809.mm b/Source/JavaScriptCore/API/tests/Regress141809.mm index 16fd373a9aa9..7eaa64bcdfde 100644 --- a/Source/JavaScriptCore/API/tests/Regress141809.mm +++ b/Source/JavaScriptCore/API/tests/Regress141809.mm @@ -44,7 +44,7 @@ @implementation TestClassA @end @protocol TestClassBExports -- (NSString *)name; +@property (nonatomic, readonly, copy) NSString *name; @end @interface TestClassB : TestClassA @@ -58,7 +58,7 @@ - (NSString *)name @end @protocol TestClassCExports -- (NSString *)name; +@property (nonatomic, readonly, copy) NSString *name; @end @interface TestClassC : TestClassB @@ -118,9 +118,9 @@ void runRegress141809() TestClassC* obj = [[TestClassC alloc] init]; resultBeforeGC = [dumpPrototypes callWithArguments:@[obj]]; } - - JSSynchronousGarbageCollectForDebugging([context JSGlobalContextRef]); - + + JSSynchronousGarbageCollectForDebugging(context.JSGlobalContextRef); + @autoreleasepool { TestClassC* obj = [[TestClassC alloc] init]; JSValue* resultAfterGC = [dumpPrototypes callWithArguments:@[obj]]; diff --git a/Source/JavaScriptCore/API/tests/testapi.mm b/Source/JavaScriptCore/API/tests/testapi.mm index a6871c88e08b..b897c69451da 100644 --- a/Source/JavaScriptCore/API/tests/testapi.mm +++ b/Source/JavaScriptCore/API/tests/testapi.mm @@ -92,7 +92,7 @@ + (NSString *)parentTest @end @protocol TestObject -- (id)init; +- (instancetype)init; @property int variable; @property (readonly) int six; @property CGPoint point; @@ -108,14 +108,14 @@ - (void)bogusCallback:(void(^)(int))function; @interface TestObject : ParentObject @property int six; -+ (id)testObject; ++ (instancetype)testObject; @end @implementation TestObject @synthesize variable; @synthesize six; @synthesize point; -+ (id)testObject ++ (instancetype)testObject { return [[TestObject alloc] init]; } @@ -144,7 +144,7 @@ - (void)bogusCallback:(void(^)(int))function bool testXYZTested = false; @protocol TextXYZ -- (id)initWithString:(NSString*)string; +- (instancetype)initWithString:(NSString *)string; @property int x; @property (readonly) int y; @property (assign) JSValue *onclick; @@ -166,7 +166,7 @@ @implementation TextXYZ { @synthesize x; @synthesize y; @synthesize z; -- (id)initWithString:(NSString*)string +- (instancetype)initWithString:(NSString *)string { self = [super init]; if (!self) @@ -225,7 +225,7 @@ @implementation TinyDOMNode { RetainPtr m_sharedVirtualMachine; } -- (id)initWithVirtualMachine:(JSVirtualMachine *)virtualMachine +- (instancetype)initWithVirtualMachine:(JSVirtualMachine *)virtualMachine { self = [super init]; if (!self) @@ -252,14 +252,14 @@ - (TinyDOMNode *)childAtIndex:(NSUInteger)index { if (index >= [m_children count]) return nil; - return [m_children objectAtIndex:index]; + return m_children[index]; } - (void)removeChildAtIndex:(NSUInteger)index { if (index >= [m_children count]) return; - [m_sharedVirtualMachine removeManagedReference:[m_children objectAtIndex:index] withOwner:self]; + [m_sharedVirtualMachine removeManagedReference:m_children[index] withOwner:self]; [m_children removeObjectAtIndex:index]; } @@ -273,7 +273,7 @@ - (JSValue *)valueForKey:(NSString *)key; @implementation JSCollection { NSMutableDictionary *_dict; } -- (id)init +- (instancetype)init { self = [super init]; if (!self) @@ -286,7 +286,7 @@ - (id)init - (void)setValue:(JSValue *)value forKey:(NSString *)key { - JSManagedValue *oldManagedValue = [_dict objectForKey:key]; + JSManagedValue *oldManagedValue = _dict[key]; if (oldManagedValue) { JSValue* oldValue = [oldManagedValue value]; if (oldValue) @@ -294,12 +294,12 @@ - (void)setValue:(JSValue *)value forKey:(NSString *)key } JSManagedValue *managedValue = [JSManagedValue managedValueWithValue:value]; [value.context.virtualMachine addManagedReference:managedValue withOwner:self]; - [_dict setObject:managedValue forKey:key]; + _dict[key] = managedValue; } - (JSValue *)valueForKey:(NSString *)key { - JSManagedValue *managedValue = [_dict objectForKey:key]; + JSManagedValue *managedValue = _dict[key]; if (!managedValue) return nil; return [managedValue value]; @@ -307,12 +307,12 @@ - (JSValue *)valueForKey:(NSString *)key @end @protocol InitA -- (id)initWithA:(int)a; +- (instancetype)initWithA:(int)a; - (int)initialize; @end @protocol InitB -- (id)initWithA:(int)a b:(int)b; +- (instancetype)initWithA:(int)a b:(int)b; @end @protocol InitC @@ -332,17 +332,17 @@ @interface ClassCPrime : ClassB @end @interface ClassD : NSObject -- (id)initWithA:(int)a; +- (instancetype)initWithA:(int)a; @end @interface ClassE : ClassD -- (id)initWithA:(int)a; +- (instancetype)initWithA:(int)a; @end @implementation ClassA { int _a; } -- (id)initWithA:(int)a +- (instancetype)initWithA:(int)a { self = [super init]; if (!self) @@ -361,7 +361,7 @@ - (int)initialize @implementation ClassB { int _b; } -- (id)initWithA:(int)a b:(int)b +- (instancetype)initWithA:(int)a b:(int)b { self = [super initWithA:a]; if (!self) @@ -376,11 +376,11 @@ - (id)initWithA:(int)a b:(int)b @implementation ClassC { int _c; } -- (id)initWithA:(int)a +- (instancetype)initWithA:(int)a { return [self initWithA:a b:0]; } -- (id)initWithA:(int)a b:(int)b +- (instancetype)initWithA:(int)a b:(int)b { self = [super initWithA:a b:b]; if (!self) @@ -393,7 +393,7 @@ - (id)initWithA:(int)a b:(int)b @end @implementation ClassCPrime -- (id)initWithA:(int)a +- (instancetype)initWithA:(int)a { self = [super initWithA:a b:0]; if (!self) @@ -408,7 +408,7 @@ - (id)_init @implementation ClassD -- (id)initWithA:(int)a +- (instancetype)initWithA:(int)a { self = nil; return [[ClassE alloc] initWithA:a]; @@ -423,7 +423,7 @@ @implementation ClassE { int _a; } -- (id)initWithA:(int)a +- (instancetype)initWithA:(int)a { self = [super init]; if (!self) @@ -444,7 +444,7 @@ - (JSValue *)doEvilThingsWithContext:(JSContext *)context; @implementation EvilAllocationObject { JSContext *m_context; } -- (id)initWithContext:(JSContext *)context +- (instancetype)initWithContext:(JSContext *)context { self = [super init]; if (!self) @@ -1763,7 +1763,7 @@ static void promiseCreateResolved() @autoreleasepool { JSContext *context = [[JSContext alloc] init]; - JSValue *promise = [JSValue valueWithNewPromiseResolvedWithResult:[NSNull null] inContext:context]; + JSValue *promise = [JSValue valueWithNewPromiseResolvedWithResult:NSNull.null inContext:context]; __block bool calledWithNull = false; [promise invokeMethod:@"then" withArguments:@[ ^(JSValue *result) { calledWithNull = [result isNull]; } @@ -1778,10 +1778,10 @@ static void promiseCreateRejected() @autoreleasepool { JSContext *context = [[JSContext alloc] init]; - JSValue *promise = [JSValue valueWithNewPromiseRejectedWithReason:[NSNull null] inContext:context]; + JSValue *promise = [JSValue valueWithNewPromiseRejectedWithReason:NSNull.null inContext:context]; __block bool calledWithNull = false; [promise invokeMethod:@"then" withArguments:@[ - [NSNull null], + NSNull.null, ^(JSValue *result) { calledWithNull = [result isNull]; } ]]; @@ -1805,7 +1805,7 @@ static void parallelPromiseResolveTest() thread = Thread::create("async thread", ^() { startedThreadPtr->store(true); while (!shouldResolveSoonPtr->load()) { } - [resolve callWithArguments:@[[NSNull null]]]; + [resolve callWithArguments:@[NSNull.null]]; }); }]; @@ -2482,13 +2482,13 @@ - (JSScript *)fetchModuleScript:(NSString *)relativePath NSLog(@"%@\n", error); CRASH(); } - [m_keyToScript setObject:result forKey:[filePath absoluteString]]; + m_keyToScript[[filePath absoluteString]] = result; return result; } - (JSScript *)findScriptForKey:(NSString *)key { - return [m_keyToScript objectForKey:key]; + return m_keyToScript[key]; } - (void)context:(JSContext *)context fetchModuleForIdentifier:(JSValue *)identifier withResolveHandler:(JSValue *)resolve andRejectHandler:(JSValue *)reject @@ -2507,7 +2507,7 @@ - (void)context:(JSContext *)context fetchModuleForIdentifier:(JSValue *)identif inVirtualMachine:context.virtualMachine error:nil]; if (script) { - [m_keyToScript setObject:script forKey:[identifier toString]]; + m_keyToScript[[identifier toString]] = script; [resolve callWithArguments:@[script]]; } else [reject callWithArguments:@[[JSValue valueWithNewErrorFromMessage:@"Unable to create Script" inContext:context]]]; diff --git a/Source/JavaScriptCore/inspector/ContentSearchUtilities.cpp b/Source/JavaScriptCore/inspector/ContentSearchUtilities.cpp index b449404e3cf6..29218c6b9bb3 100644 --- a/Source/JavaScriptCore/inspector/ContentSearchUtilities.cpp +++ b/Source/JavaScriptCore/inspector/ContentSearchUtilities.cpp @@ -49,7 +49,7 @@ static String escapeStringForRegularExpressionSource(const String& text) { StringBuilder result; - for (unsigned i = 0; i < text.length(); i++) { + for (size_t i = 0; i < text.length(); i++) { UChar character = text[i]; if (isASCII(character) && strchr(regexSpecialCharacters, character)) result.append('\\'); @@ -155,12 +155,12 @@ int countRegularExpressionMatches(const RegularExpression& regex, const String& int position; unsigned start = 0; int matchLength; - while ((position = regex.match(content, start, &matchLength)) != -1) { - if (start >= content.length()) - break; + while ((position = regex.match(content, start, &matchLength)) >= 0) { if (matchLength > 0) ++result; start = position + 1; + if (start >= content.length()) + break; } return result; } diff --git a/Source/JavaScriptCore/inspector/remote/cocoa/RemoteInspectorCocoa.mm b/Source/JavaScriptCore/inspector/remote/cocoa/RemoteInspectorCocoa.mm index 6bc571115b6c..041993e41c6e 100644 --- a/Source/JavaScriptCore/inspector/remote/cocoa/RemoteInspectorCocoa.mm +++ b/Source/JavaScriptCore/inspector/remote/cocoa/RemoteInspectorCocoa.mm @@ -63,7 +63,7 @@ static void convertNSNullToNil(__strong NSNumber *& number) { - if ([number isEqual:[NSNull null]]) + if ([number isEqual:NSNull.null]) number = nil; } @@ -461,32 +461,32 @@ static bool canAccessWebInspectorMachPort() if (!target.allowsInspectionByPolicy()) return nil; - RetainPtr listing = adoptNS([[NSMutableDictionary alloc] init]); - [listing setObject:@(target.targetIdentifier()) forKey:WIRTargetIdentifierKey]; + NSMutableDictionary *listing = [[NSMutableDictionary alloc] init]; + listing[WIRTargetIdentifierKey] = @(target.targetIdentifier()); switch (target.type()) { case RemoteInspectionTarget::Type::ITML: - [listing setObject:target.name() forKey:WIRTitleKey]; - [listing setObject:WIRTypeITML forKey:WIRTypeKey]; + listing[WIRTitleKey] = target.name(); + listing[WIRTypeKey] = WIRTypeITML; break; case RemoteInspectionTarget::Type::JavaScript: - [listing setObject:target.name() forKey:WIRTitleKey]; - [listing setObject:WIRTypeJavaScript forKey:WIRTypeKey]; + listing[WIRTitleKey] = target.name(); + listing[WIRTypeKey] = WIRTypeJavaScript; break; case RemoteInspectionTarget::Type::Page: - [listing setObject:target.url() forKey:WIRURLKey]; - [listing setObject:target.name() forKey:WIRTitleKey]; - [listing setObject:WIRTypePage forKey:WIRTypeKey]; + listing[WIRURLKey] = target.url(); + listing[WIRTitleKey] = target.name(); + listing[WIRTypeKey] = WIRTypePage; break; case RemoteInspectionTarget::Type::ServiceWorker: - [listing setObject:target.url() forKey:WIRURLKey]; - [listing setObject:target.name() forKey:WIRTitleKey]; - [listing setObject:WIRTypeServiceWorker forKey:WIRTypeKey]; + listing[WIRURLKey] = target.url(); + listing[WIRTitleKey] = target.name(); + listing[WIRTypeKey] = WIRTypeServiceWorker; break; case RemoteInspectionTarget::Type::WebPage: - [listing setObject:target.url() forKey:WIRURLKey]; - [listing setObject:target.name() forKey:WIRTitleKey]; - [listing setObject:WIRTypeWebPage forKey:WIRTypeKey]; + listing[WIRURLKey] = target.url(); + listing[WIRTitleKey] = target.name(); + listing[WIRTypeKey] = WIRTypeWebPage; break; default: ASSERT_NOT_REACHED(); @@ -494,12 +494,12 @@ static bool canAccessWebInspectorMachPort() } if (auto* connectionToTarget = m_targetConnectionMap.get(target.targetIdentifier())) - [listing setObject:connectionToTarget->connectionIdentifier() forKey:WIRConnectionIdentifierKey]; + listing[WIRConnectionIdentifierKey] = connectionToTarget->connectionIdentifier(); if (target.hasLocalDebugger()) - [listing setObject:@YES forKey:WIRHasLocalDebuggerKey]; + listing[WIRHasLocalDebuggerKey] = @YES; - return listing; + return adoptNS(listing); } RetainPtr RemoteInspector::listingForAutomationTarget(const RemoteAutomationTarget& target) const @@ -511,20 +511,20 @@ static bool canAccessWebInspectorMachPort() if (target.isPendingTermination()) return nullptr; - RetainPtr listing = adoptNS([[NSMutableDictionary alloc] init]); - [listing setObject:@(target.targetIdentifier()) forKey:WIRTargetIdentifierKey]; - [listing setObject:target.name() forKey:WIRSessionIdentifierKey]; - [listing setObject:WIRTypeAutomation forKey:WIRTypeKey]; - [listing setObject:@(target.isPaired()) forKey:WIRAutomationTargetIsPairedKey]; + NSMutableDictionary *listing = [[NSMutableDictionary alloc] init]; + listing[WIRTargetIdentifierKey] = @(target.targetIdentifier()); + listing[WIRSessionIdentifierKey] = target.name(); + listing[WIRTypeKey] = WIRTypeAutomation; + listing[WIRAutomationTargetIsPairedKey] = @(target.isPaired()); if (m_clientCapabilities) { - [listing setObject:m_clientCapabilities->browserName forKey:WIRAutomationTargetNameKey]; - [listing setObject:m_clientCapabilities->browserVersion forKey:WIRAutomationTargetVersionKey]; + listing[WIRAutomationTargetNameKey] = m_clientCapabilities->browserName; + listing[WIRAutomationTargetVersionKey] = m_clientCapabilities->browserVersion; } if (auto connectionToTarget = m_targetConnectionMap.get(target.targetIdentifier())) - [listing setObject:connectionToTarget->connectionIdentifier() forKey:WIRConnectionIdentifierKey]; + listing[WIRConnectionIdentifierKey] = connectionToTarget->connectionIdentifier(); - return listing; + return adoptNS(listing); } void RemoteInspector::pushListingsNow() @@ -535,27 +535,27 @@ static bool canAccessWebInspectorMachPort() m_pushScheduled = false; - RetainPtr listings = adoptNS([[NSMutableDictionary alloc] init]); + NSMutableDictionary *listings = NSMutableDictionary.dictionary; for (const auto& listing : m_targetListingMap.values()) { - NSString *targetIdentifierString = [[listing.get() objectForKey:WIRTargetIdentifierKey] stringValue]; - [listings setObject:listing.get() forKey:targetIdentifierString]; + NSString *targetIdentifierString = [listing.get()[WIRTargetIdentifierKey] stringValue]; + listings[targetIdentifierString] = listing.get(); } - RetainPtr message = adoptNS([[NSMutableDictionary alloc] init]); - [message setObject:listings.get() forKey:WIRListingKey]; - - if (!m_clientCapabilities) - [message setObject:WIRAutomationAvailabilityUnknown forKey:WIRAutomationAvailabilityKey]; - else if (m_clientCapabilities->remoteAutomationAllowed) - [message setObject:WIRAutomationAvailabilityAvailable forKey:WIRAutomationAvailabilityKey]; - else - [message setObject:WIRAutomationAvailabilityNotAvailable forKey:WIRAutomationAvailabilityKey]; - - // COMPATIBILITY(iOS 13): this key is deprecated and not used by newer versions of webinspectord. - BOOL isAllowed = m_clientCapabilities && m_clientCapabilities->remoteAutomationAllowed; - [message setObject:@(isAllowed) forKey:WIRRemoteAutomationEnabledKey]; + NSString *availabilityKey; + NSNumber *isAllowed; // COMPATIBILITY(iOS 13): WIRRemoteAutomationEnabledKey is deprecated and not used by newer versions of webinspectord. + + if (!m_clientCapabilities) { + availabilityKey = WIRAutomationAvailabilityUnknown; + isAllowed = @NO; + } else if (m_clientCapabilities->remoteAutomationAllowed) { + availabilityKey = WIRAutomationAvailabilityAvailable; + isAllowed = @YES; + } else { + availabilityKey = WIRAutomationAvailabilityNotAvailable; + isAllowed = @NO; + } - m_relayConnection->sendMessage(WIRListingMessage, message.get()); + m_relayConnection->sendMessage(WIRListingMessage, @{ WIRListingKey: listings, WIRAutomationAvailabilityKey: availabilityKey, WIRRemoteAutomationEnabledKey: isAllowed }); } void RemoteInspector::pushListingsSoon() diff --git a/Source/JavaScriptCore/inspector/remote/cocoa/RemoteInspectorXPCConnection.mm b/Source/JavaScriptCore/inspector/remote/cocoa/RemoteInspectorXPCConnection.mm index aeff68b47983..42d658149f68 100644 --- a/Source/JavaScriptCore/inspector/remote/cocoa/RemoteInspectorXPCConnection.mm +++ b/Source/JavaScriptCore/inspector/remote/cocoa/RemoteInspectorXPCConnection.mm @@ -175,12 +175,13 @@ if (m_closed) return; - auto dictionary = adoptNS([[NSMutableDictionary alloc] init]); - [dictionary setObject:messageName forKey:RemoteInspectorXPCConnectionMessageNameKey]; + NSDictionary *dictionary; if (userInfo) - [dictionary setObject:userInfo forKey:RemoteInspectorXPCConnectionUserInfoKey]; + dictionary = @{ RemoteInspectorXPCConnectionUserInfoKey : userInfo, RemoteInspectorXPCConnectionMessageNameKey : messageName }; + else + dictionary = @{ RemoteInspectorXPCConnectionMessageNameKey : messageName }; - auto xpcDictionary = adoptOSObject(_CFXPCCreateXPCMessageWithCFObject((__bridge CFDictionaryRef)dictionary.get())); + auto xpcDictionary = adoptOSObject(_CFXPCCreateXPCMessageWithCFObject((__bridge CFDictionaryRef)dictionary)); ASSERT_WITH_MESSAGE(xpcDictionary && xpc_get_type(xpcDictionary.get()) == XPC_TYPE_DICTIONARY, "Unable to serialize xpc message"); if (!xpcDictionary) return; diff --git a/Source/JavaScriptCore/testmem/testmem.mm b/Source/JavaScriptCore/testmem/testmem.mm index 9bc4b40e1eac..6d47a0c9e1a9 100644 --- a/Source/JavaScriptCore/testmem/testmem.mm +++ b/Source/JavaScriptCore/testmem/testmem.mm @@ -74,7 +74,7 @@ int main(int argc, char* argv[]) iterations = iters; } - NSString *path = [NSString stringWithUTF8String:argv[1]]; + NSString *path = @(argv[1]); NSString *script = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; if (!script) { printf("Can't open file: %s\n", argv[1]); diff --git a/Source/WTF/wtf/cocoa/FileSystemCocoa.mm b/Source/WTF/wtf/cocoa/FileSystemCocoa.mm index 5c89b97c1c56..61d6f82540be 100644 --- a/Source/WTF/wtf/cocoa/FileSystemCocoa.mm +++ b/Source/WTF/wtf/cocoa/FileSystemCocoa.mm @@ -76,17 +76,17 @@ String createTemporaryZipArchive(const String& path) CString archivePath([NSTemporaryDirectory() stringByAppendingPathComponent:@"WebKitGeneratedFileXXXXXX"].fileSystemRepresentation); if (mkstemp(archivePath.mutableData()) == -1) return; - - NSDictionary *options = @{ - (__bridge id)kBOMCopierOptionCreatePKZipKey : @YES, - (__bridge id)kBOMCopierOptionSequesterResourcesKey : @YES, - (__bridge id)kBOMCopierOptionKeepParentKey : @YES, - (__bridge id)kBOMCopierOptionCopyResourcesKey : @YES, - }; - + + CFTypeRef keys[] = { kBOMCopierOptionCreatePKZipKey, kBOMCopierOptionSequesterResourcesKey, kBOMCopierOptionKeepParentKey, kBOMCopierOptionCopyResourcesKey }; + CFTypeRef values[] = { kCFBooleanTrue, kCFBooleanTrue, kCFBooleanTrue, kCFBooleanTrue }; + + CFDictionaryRef options = CFDictionaryCreate(kCFAllocatorDefault, keys, values, sizeof(keys) / sizeof(keys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); BOMCopier copier = BOMCopierNew(); - if (!BOMCopierCopyWithOptions(copier, newURL.path.fileSystemRepresentation, archivePath.data(), (__bridge CFDictionaryRef)options)) + + if (!BOMCopierCopyWithOptions(copier, newURL.path.fileSystemRepresentation, archivePath.data(), options)) temporaryFile = String::fromUTF8(archivePath); + + CFRelease(options); BOMCopierFree(copier); }]; @@ -126,14 +126,14 @@ String openTemporaryFile(StringView prefix, PlatformFileHandle& platformFileHand NSString *createTemporaryDirectory(NSString *directoryPrefix) { NSString *tempDirectory = NSTemporaryDirectory(); - if (!tempDirectory || ![tempDirectory length]) + if (!tempDirectory || !tempDirectory.length) return nil; - if (!directoryPrefix || ![directoryPrefix length]) + if (!directoryPrefix || !directoryPrefix.length) return nil; NSString *tempDirectoryComponent = [directoryPrefix stringByAppendingString:@"-XXXXXXXX"]; - const char* tempDirectoryCString = [[tempDirectory stringByAppendingPathComponent:tempDirectoryComponent] fileSystemRepresentation]; + const char* tempDirectoryCString = [tempDirectory stringByAppendingPathComponent:tempDirectoryComponent].fileSystemRepresentation; if (!tempDirectoryCString) return nil; @@ -204,7 +204,7 @@ bool isSafeToUseMemoryMapForPath(const String& path) LOG_ERROR("Unable to get path protection class"); return false; } - if ([[attributes objectForKey:NSFileProtectionKey] isEqualToString:NSFileProtectionComplete]) { + if ([attributes[NSFileProtectionKey] isEqualToString:NSFileProtectionComplete]) { LOG_ERROR("Path protection class is NSFileProtectionComplete, so it is not safe to use memory map"); return false; } @@ -232,7 +232,7 @@ bool setExcludedFromBackup(const String& path, bool excluded) return false; NSError *error; - if (![[NSURL fileURLWithPath:(NSString *)path isDirectory:YES] setResourceValue:[NSNumber numberWithBool:excluded] forKey:NSURLIsExcludedFromBackupKey error:&error]) { + if (![[NSURL fileURLWithPath:(NSString *)path isDirectory:YES] setResourceValue:@(excluded) forKey:NSURLIsExcludedFromBackupKey error:&error]) { LOG_ERROR("Cannot exclude path '%s' from backup with error '%@'", path.utf8().data(), error.localizedDescription); return false; } diff --git a/Source/WTF/wtf/cocoa/LanguageCocoa.mm b/Source/WTF/wtf/cocoa/LanguageCocoa.mm index 1d8a838e6700..cf51290f7ee6 100644 --- a/Source/WTF/wtf/cocoa/LanguageCocoa.mm +++ b/Source/WTF/wtf/cocoa/LanguageCocoa.mm @@ -40,12 +40,12 @@ size_t indexOfBestMatchingLanguageInList(const String& language, const Vector& languageList, bool& exactMatch) { auto matchedLanguages = retainPtr([NSLocale matchedLanguagesFromAvailableLanguages:createNSArray(languageList).get() forPreferredLanguages:@[ static_cast(language) ]]); - if (![matchedLanguages count]) { + if (!matchedLanguages.get().count) { exactMatch = false; return languageList.size(); } - String firstMatchedLanguage = [matchedLanguages firstObject]; + String firstMatchedLanguage = matchedLanguages.get().firstObject; exactMatch = language == firstMatchedLanguage; diff --git a/Source/WTF/wtf/cocoa/NSURLExtras.mm b/Source/WTF/wtf/cocoa/NSURLExtras.mm index 2087440b0f6f..3246169cec54 100644 --- a/Source/WTF/wtf/cocoa/NSURLExtras.mm +++ b/Source/WTF/wtf/cocoa/NSURLExtras.mm @@ -45,7 +45,7 @@ static BOOL readIDNAllowedScriptListFile(NSString *filename) if (!filename) return NO; - FILE *file = fopen([filename fileSystemRepresentation], "r"); + FILE* file = fopen(filename.fileSystemRepresentation, "r"); if (!file) return NO; @@ -140,13 +140,13 @@ static String decodePercentEscapes(const String& string) { if (!data) return nil; - - size_t length = [data length]; - if (length > 0) { + + NSUInteger length = data.length; + if (length) { // Work around : CFURLCreateAbsoluteURLWithBytes(.., TRUE) doesn't remove non-path components. baseURL = URLByTruncatingOneCharacterBeforeComponent(baseURL, kCFURLComponentResourceSpecifier); - const UInt8 *bytes = static_cast([data bytes]); + const UInt8 *bytes = static_cast(data.bytes); // CFURLCreateAbsoluteURLWithBytes would complain to console if we passed a path to it. if (bytes[0] == '/' && !baseURL) @@ -156,9 +156,9 @@ static String decodePercentEscapes(const String& string) // (e.g calls to NSURL -path). However, this function is not tolerant of illegal UTF-8 sequences, which // could either be a malformed string or bytes in a different encoding, like shift-jis, so we fall back // onto using ISO Latin 1 in those cases. - auto result = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, bytes, length, kCFStringEncodingUTF8, (__bridge CFURLRef)baseURL, YES)); + auto result = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, bytes, (CFIndex)length, kCFStringEncodingUTF8, (__bridge CFURLRef)baseURL, YES)); if (!result) - result = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, bytes, length, kCFStringEncodingISOLatin1, (__bridge CFURLRef)baseURL, YES)); + result = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, bytes, (CFIndex)length, kCFStringEncodingISOLatin1, (__bridge CFURLRef)baseURL, YES)); return result.bridgingAutorelease(); } return [NSURL URLWithString:@""]; @@ -168,21 +168,21 @@ static String decodePercentEscapes(const String& string) { NSData *userTypedData = [string dataUsingEncoding:NSUTF8StringEncoding]; ASSERT(userTypedData); - - const UInt8* inBytes = static_cast([userTypedData bytes]); - int inLength = [userTypedData length]; + + const UInt8 *inBytes = static_cast(userTypedData.bytes); + NSUInteger inLength = userTypedData.length; if (!inLength) return nil; - CheckedInt32 mallocLength = inLength; - mallocLength *= 3; // large enough to %-escape every character + CheckedSize mallocLength = inLength; + mallocLength *= (size_t)3; // large enough to %-escape every character if (mallocLength.hasOverflowed()) return nil; char* outBytes = static_cast(malloc(mallocLength)); char* p = outBytes; - int outLength = 0; - for (int i = 0; i < inLength; i++) { + NSUInteger outLength = 0; + for (NSUInteger i = 0; i < inLength; i++) { UInt8 c = inBytes[i]; if (c <= 0x20 || c >= 0x7f) { *p++ = '%'; @@ -194,7 +194,7 @@ static String decodePercentEscapes(const String& string) outLength++; } } - + return [NSData dataWithBytesNoCopy:outBytes length:outLength]; // adopts outBytes } @@ -317,17 +317,14 @@ static bool hasQuestionMarkOnlyQueryString(NSURL *URL) NSString *userVisibleString(NSURL *URL) { NSData *data = originalURLData(URL); - return URLHelpers::userVisibleURL(CString(static_cast([data bytes]), [data length])); + return URLHelpers::userVisibleURL(CString(static_cast(data.bytes), data.length)); } BOOL isUserVisibleURL(NSString *string) { // Return true if the userVisibleString function is guaranteed to not change the passed-in URL. // This function is used to optimize all the most common cases where we don't need the userVisibleString algorithm. - - char buffer[1024]; - auto success = CFStringGetCString(bridge_cast(string), reinterpret_cast(buffer), sizeof(buffer) - 1, kCFStringEncodingUTF8); - auto characters = success ? buffer : [string UTF8String]; + auto characters = string.UTF8String; // Check for control characters, %-escape sequences that are non-ASCII, and xn--: these // are the things that might lead the userVisibleString function to actually change the string. diff --git a/Source/WebCore/bridge/objc/objc_utility.mm b/Source/WebCore/bridge/objc/objc_utility.mm index 7078ad5d689c..a415807b6483 100644 --- a/Source/WebCore/bridge/objc/objc_utility.mm +++ b/Source/WebCore/bridge/objc/objc_utility.mm @@ -252,10 +252,10 @@ JSValue convertObjcValueToValue(JSGlobalObject* lexicalGlobalObject, void* buffe ObjcValueType objcValueTypeForType(const char *type) { - int typeLength = strlen(type); + size_t typeLength = strlen(type); ObjcValueType objcValueType = ObjcInvalidType; - for (int i = 0; i < typeLength; ++i) { + for (size_t i = 0; i < typeLength; ++i) { char typeChar = type[i]; switch (typeChar) { case _C_CONST: diff --git a/Source/WebCore/platform/graphics/transforms/TransformationMatrix.cpp b/Source/WebCore/platform/graphics/transforms/TransformationMatrix.cpp index deeb9900bb52..28a734123f3f 100644 --- a/Source/WebCore/platform/graphics/transforms/TransformationMatrix.cpp +++ b/Source/WebCore/platform/graphics/transforms/TransformationMatrix.cpp @@ -68,7 +68,7 @@ namespace WebCore { typedef double Vector4[4]; typedef double Vector3[3]; -const double SMALL_NUMBER = 1.e-8; +constexpr double SMALL_NUMBER = 1.e-8; const TransformationMatrix TransformationMatrix::identity { }; @@ -218,9 +218,10 @@ static bool inverse(const TransformationMatrix::Matrix4& matrix, TransformationM // Scale the adjoint matrix to get the inverse - for (int i = 0; i < 4; i++) - for (int j = 0; j < 4; j++) + for (unsigned i = 0; i < 4; i++) { + for (unsigned j = 0; j < 4; j++) result[i][j] = result[i][j] / det; + } return true; } @@ -233,9 +234,10 @@ static bool inverse(const TransformationMatrix::Matrix4& matrix, TransformationM // Transpose rotation portion of matrix a, return b static void transposeMatrix4(const TransformationMatrix::Matrix4& a, TransformationMatrix::Matrix4& b) { - for (int i = 0; i < 4; i++) - for (int j = 0; j < 4; j++) + for (unsigned i = 0; i < 4; i++) { + for (unsigned j = 0; j < 4; j++) b[i][j] = a[j][i]; + } } // Multiply a homogeneous point by a matrix and return the transformed point @@ -360,10 +362,11 @@ static bool decompose4(const TransformationMatrix::Matrix4& mat, TransformationM if (localMatrix[3][3] == 0) return false; - int i, j; - for (i = 0; i < 4; i++) + unsigned i, j; + for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) localMatrix[i][j] /= localMatrix[3][3]; + } // perspectiveMatrix is used to solve for perspective, but it also provides // an easy way to test for singularity of the upper 3x3 component. @@ -683,7 +686,7 @@ FloatPoint TransformationMatrix::projectPoint(const FloatPoint& p, bool* clamped // Using int max causes overflow when other code uses the projected point. To // represent infinity yet reduce the risk of overflow, we use a large but // not-too-large number here when clamping. - const int largeNumber = 100000000 / kFixedPointDenominator; + constexpr int largeNumber = 100000000 / kFixedPointDenominator; outX = copysign(largeNumber, outX); outY = copysign(largeNumber, outY); if (clamped) diff --git a/Source/WebCore/platform/mac/PluginBlocklist.mm b/Source/WebCore/platform/mac/PluginBlocklist.mm index c7355f2760b7..078dd4f7e334 100644 --- a/Source/WebCore/platform/mac/PluginBlocklist.mm +++ b/Source/WebCore/platform/mac/PluginBlocklist.mm @@ -64,20 +64,20 @@ auto systemVersionDictionary = adoptCF(_CFCopySystemVersionDictionary()); CFStringRef osVersion = static_cast(CFDictionaryGetValue(systemVersionDictionary.get(), _kCFSystemVersionProductVersionKey)); - NSDictionary *dictionary = [propertyList objectForKey:@"PlugInBlocklist"]; + NSDictionary *dictionary = propertyList[@"PlugInBlocklist"]; + + NSMutableDictionary *bundleIDToMinimumSecureVersion = NSMutableDictionary.dictionary; + NSMutableDictionary *bundleIDToMinimumCompatibleVersion = NSMutableDictionary.dictionary; + NSMutableDictionary *bundleIDToBlockedVersions = NSMutableDictionary.dictionary; + NSMutableSet *bundleIDsWithAvailableUpdates = NSMutableSet.set; - NSMutableDictionary *bundleIDToMinimumSecureVersion = [NSMutableDictionary dictionary]; - NSMutableDictionary *bundleIDToMinimumCompatibleVersion = [NSMutableDictionary dictionary]; - NSMutableDictionary *bundleIDToBlockedVersions = [NSMutableDictionary dictionary]; - NSMutableSet *bundleIDsWithAvailableUpdates = [NSMutableSet set]; - for (NSString *osVersionComponent in splitOSVersion((__bridge NSString *)osVersion)) { NSDictionary *bundleIDs = [dictionary objectForKey:osVersionComponent]; if (!bundleIDs) continue; for (NSString *bundleID in bundleIDs) { - NSDictionary *versionInfo = [bundleIDs objectForKey:bundleID]; + NSDictionary *versionInfo = bundleIDs[bundleID]; assert(versionInfo); if (![versionInfo isKindOfClass:[NSDictionary class]]) @@ -87,16 +87,16 @@ [bundleIDToMinimumCompatibleVersion removeObjectForKey:bundleID]; [bundleIDToBlockedVersions removeObjectForKey:bundleID]; - if (NSArray *blockedVersions = [versionInfo objectForKey:@"BlockedPlugInBundleVersions"]) - [bundleIDToBlockedVersions setObject:blockedVersions forKey:bundleID]; + if (NSArray *blockedVersions = versionInfo[@"BlockedPlugInBundleVersions"]) + bundleIDToBlockedVersions[bundleID] = blockedVersions; - if (NSString *minimumSecureVersion = [versionInfo objectForKey:@"MinimumPlugInBundleVersion"]) - [bundleIDToMinimumSecureVersion setObject:minimumSecureVersion forKey:bundleID]; + if (NSString *minimumSecureVersion = versionInfo[@"MinimumPlugInBundleVersion"]) + bundleIDToMinimumSecureVersion[bundleID] = minimumSecureVersion; - if (NSString *minimumCompatibleVersion = [versionInfo objectForKey:@"MinimumCompatiblePlugInBundleVersion"]) - [bundleIDToMinimumCompatibleVersion setObject:minimumCompatibleVersion forKey:bundleID]; + if (NSString *minimumCompatibleVersion = versionInfo[@"MinimumCompatiblePlugInBundleVersion"]) + bundleIDToMinimumCompatibleVersion[bundleID] = minimumCompatibleVersion; - if (NSNumber *updateAvailable = [versionInfo objectForKey:@"PlugInUpdateAvailable"]) { + if (NSNumber *updateAvailable = versionInfo[@"PlugInUpdateAvailable"]) { // A missing PlugInUpdateAvailable key means that there is a plug-in update available. if (!updateAvailable || [updateAvailable boolValue]) [bundleIDsWithAvailableUpdates addObject:bundleID]; diff --git a/Source/WebGPU/WebGPU/Adapter.mm b/Source/WebGPU/WebGPU/Adapter.mm index c3a4d22ec21f..5050e716220f 100644 --- a/Source/WebGPU/WebGPU/Adapter.mm +++ b/Source/WebGPU/WebGPU/Adapter.mm @@ -79,7 +79,7 @@ bool Adapter::hasFeature(WGPUFeatureName feature) { - return std::find(m_capabilities.features.begin(), m_capabilities.features.end(), feature); + return m_capabilities.features.find(feature); } void Adapter::requestDevice(const WGPUDeviceDescriptor& descriptor, CompletionHandler&&, String&&)>&& callback) diff --git a/Source/WebGPU/WebGPU/Device.mm b/Source/WebGPU/WebGPU/Device.mm index c2aaabfb64a3..86551ef27c98 100644 --- a/Source/WebGPU/WebGPU/Device.mm +++ b/Source/WebGPU/WebGPU/Device.mm @@ -82,13 +82,13 @@ static void registerForFrameCapture(id captureObject) static void captureFrame(id captureObject) { MTLCaptureManager* captureManager = [MTLCaptureManager sharedCaptureManager]; - if ([captureManager isCapturing]) + if (captureManager.isCapturing) return; MTLCaptureDescriptor* captureDescriptor = [[MTLCaptureDescriptor alloc] init]; captureDescriptor.captureObject = captureObject; captureDescriptor.destination = MTLCaptureDestinationGPUTraceDocument; - captureDescriptor.outputURL = [[NSFileManager.defaultManager temporaryDirectory] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.gputrace", NSUUID.UUID.UUIDString]]; + captureDescriptor.outputURL = [NSFileManager.defaultManager.temporaryDirectory URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.gputrace", NSUUID.UUID.UUIDString]]; NSError *error; if (![captureManager startCaptureWithDescriptor:captureDescriptor error:&error]) @@ -221,7 +221,7 @@ static void captureFrame(id captureObject) bool Device::hasFeature(WGPUFeatureName feature) { - return std::find(m_capabilities.features.begin(), m_capabilities.features.end(), feature); + return m_capabilities.features.find(feature); } auto Device::currentErrorScope(WGPUErrorFilter type) -> ErrorScope* diff --git a/Source/WebGPU/WebGPU/HardwareCapabilities.mm b/Source/WebGPU/WebGPU/HardwareCapabilities.mm index 3498a11c8474..7b55188e18a5 100644 --- a/Source/WebGPU/WebGPU/HardwareCapabilities.mm +++ b/Source/WebGPU/WebGPU/HardwareCapabilities.mm @@ -67,7 +67,7 @@ static constexpr uint32_t maxUInt32Limit() timestampCounterSet = nil; return { - [device argumentBuffersSupport], + device.argumentBuffersSupport, false, // To be filled in by the caller. timestampCounterSet, statisticCounterSet, diff --git a/Source/WebKit/UIProcess/API/Cocoa/APIContentRuleListStoreCocoa.mm b/Source/WebKit/UIProcess/API/Cocoa/APIContentRuleListStoreCocoa.mm index 38cd96ca408b..3faa8b2c8471 100644 --- a/Source/WebKit/UIProcess/API/Cocoa/APIContentRuleListStoreCocoa.mm +++ b/Source/WebKit/UIProcess/API/Cocoa/APIContentRuleListStoreCocoa.mm @@ -46,9 +46,9 @@ url = [url URLByAppendingPathComponent:@"WebKit" isDirectory:YES]; if (!WebKit::processHasContainer()) { - NSString *bundleIdentifier = [NSBundle mainBundle].bundleIdentifier; + NSString *bundleIdentifier = NSBundle.mainBundle.bundleIdentifier; if (!bundleIdentifier) - bundleIdentifier = [NSProcessInfo processInfo].processName; + bundleIdentifier = NSProcessInfo.processInfo.processName; url = [url URLByAppendingPathComponent:bundleIdentifier isDirectory:YES]; } diff --git a/Source/WebKit/UIProcess/Extensions/Cocoa/WebExtensionControllerConfiguration.mm b/Source/WebKit/UIProcess/Extensions/Cocoa/WebExtensionControllerConfiguration.mm index e10dcff4cbb4..4db9c59c74d6 100644 --- a/Source/WebKit/UIProcess/Extensions/Cocoa/WebExtensionControllerConfiguration.mm +++ b/Source/WebKit/UIProcess/Extensions/Cocoa/WebExtensionControllerConfiguration.mm @@ -53,7 +53,7 @@ return; } - String appDirectoryName = [NSBundle mainBundle].bundleIdentifier ?: [NSProcessInfo processInfo].processName; + String appDirectoryName = NSBundle.mainBundle.bundleIdentifier ?: NSProcessInfo.processInfo.processName; defaultStoragePath.get() = FileSystem::pathByAppendingComponents(libraryPath, { "WebKit"_s, appDirectoryName, "WebExtensions"_s, identifierPath }); }); diff --git a/Source/WebKit/UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm b/Source/WebKit/UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm index 3b5bca7fd387..34baf4c4267a 100644 --- a/Source/WebKit/UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm +++ b/Source/WebKit/UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm @@ -100,8 +100,8 @@ static bool experimentalFeatureEnabled(const String& key, bool defaultValue = fa static NSString* applicationOrProcessIdentifier() { - NSString *identifier = [NSBundle mainBundle].bundleIdentifier; - NSString *processName = [NSProcessInfo processInfo].processName; + NSString *identifier = NSBundle.mainBundle.bundleIdentifier; + NSString *processName = NSProcessInfo.processInfo.processName; // SafariForWebKitDevelopment has the same bundle identifier as Safari, but it does not have the privilege to // access Safari's paths. if ([identifier isEqualToString:@"com.apple.Safari"] && [processName isEqualToString:@"SafariForWebKitDevelopment"]) diff --git a/Source/bmalloc/bmalloc/ProcessCheck.mm b/Source/bmalloc/bmalloc/ProcessCheck.mm index 7f71d15d8ceb..013225db0a30 100644 --- a/Source/bmalloc/bmalloc/ProcessCheck.mm +++ b/Source/bmalloc/bmalloc/ProcessCheck.mm @@ -38,12 +38,12 @@ bool gigacageEnabledForProcess() // If we wanted to make it efficient to call more than once, we could memoize the result in a global boolean. @autoreleasepool { - if (NSString *appName = [[NSBundle mainBundle] bundleIdentifier]) { + if (NSString *appName = NSBundle.mainBundle.bundleIdentifier) { bool isWebProcess = [appName hasPrefix:@"com.apple.WebKit.WebContent"]; return isWebProcess; } - NSString *processName = [[NSProcessInfo processInfo] processName]; + NSString *processName = NSProcessInfo.processInfo.processName; bool isOptInBinary = [processName isEqualToString:@"jsc"] || [processName isEqualToString:@"DumpRenderTree"] || [processName isEqualToString:@"wasm"] @@ -78,13 +78,13 @@ bool shouldProcessUnconditionallyUseBmalloc() static std::once_flag onceFlag; std::call_once(onceFlag, [&] () { @autoreleasepool { - if (NSString *appName = [[NSBundle mainBundle] bundleIdentifier]) { + if (NSString *appName = NSBundle.mainBundle.bundleIdentifier) { auto contains = [&] (NSString *string) { return [appName rangeOfString:string options:NSCaseInsensitiveSearch].location != NSNotFound; }; result = contains(@"com.apple.WebKit") || contains(@"safari"); } else { - NSString *processName = [[NSProcessInfo processInfo] processName]; + NSString *processName = NSProcessInfo.processInfo.processName; result = [processName isEqualToString:@"jsc"] || [processName isEqualToString:@"wasm"] || [processName hasPrefix:@"test"];