Cline rules
.clinerules/04-Code-style-guidelines.mdCline rules
Quality
69/100
Scores the file, not the repository.Length
1,817 words
44 headings · 25 code blocksRepository
344
— · pushed 0 days agoLast changed
3 days ago
First indexed 3 days ago.1# Objective-C Code Style Guidelines for AI Agents23## Overview45This document provides code style guidelines that AI agents MUST follow when working with this Objective-C codebase. These guidelines are adapted from industry best practices and tailored to match the existing code patterns in this repository.67## Key Principles89### RFC 2119 Compliance1011- **MUST**: Absolute requirement12- **MUST NOT**: Absolute prohibition13- **SHOULD**: Recommended but may have valid reasons to ignore14- **SHOULD NOT**: Not recommended but may have valid reasons to use15- **MAY**: Optional1617---1819## Code Style Rules2021### 1. Dot Notation Syntax2223**RECOMMENDED:** Use dot notation for getting and setting properties.2425```objc26// Preferred27view.backgroundColor = UIColor.orangeColor;28NSString *username = account.username;2930// Avoid31[view setBackgroundColor:[UIColor orangeColor]];32NSString *username = [account username];33```3435### 2. Spacing and Indentation3637**MUST** follow these spacing rules:3839- Indentation: 4 spaces (never tabs)40- **Opening braces on NEW line** (repository convention)41- Closing braces on new line42- One blank line between methods4344```objc45// Correct (as used in this repository)46- (instancetype)initWithUsername:(NSString *)username47 homeAccountId:(MSALAccountId *)homeAccountId48 environment:(NSString *)environment49{50 self = [super init];5152 if (self)53 {54 _username = username;55 _environment = environment;56 _homeAccountId = homeAccountId;57 }5859 return self;60}6162// For if/else statements63if (user.isHappy)64{65 // Do something66}67else68{69 // Do something else70}71```7273### 3. Conditionals7475**MUST** always use braces for conditional bodies, even for single-line statements.7677```objc78// Correct79if (!error)80{81 return success;82}8384// Incorrect - Never do this85if (!error)86 return success;8788if (!error) return success;89```9091### 4. Ternary Operator9293**SHOULD** only evaluate a single condition per ternary expression.9495```objc96// Acceptable97result = account.isValid ? account : nil;9899// Avoid - too complex100result = account.isValid ? account.username = tenant.isValid ? tenant.id : nil : nil;101```102103### 5. Error Handling104105**MUST** check the return value, **MUST NOT** check the error variable directly.106107```objc108// Correct109NSError *error;110if (![self trySomethingWithError:&error])111{112 // Handle Error113}114115// Incorrect - Apple APIs may write garbage to error on success116NSError *error;117[self trySomethingWithError:&error];118if (error)119{120 // Handle Error121}122```123124### 6. Method Signatures125126**SHOULD** include space after scope symbol and between method segments.127128```objc129// Correct130- (void)acquireTokenWithParameters:(MSALSilentTokenParameters *)parameters131 completionBlock:(MSALCompletionBlock)completionBlock;132133// For methods exceeding 80 characters, format like a form134- (MSALResult *)resultWithTokenResult:(MSIDTokenResult *)result135 authScheme:(id<MSALAuthenticationSchemeProtocol>)authScheme136 popManager:(MSIDDevicePopManager *)popManager137 error:(NSError **)error;138```139140### 7. Variables141142#### Naming143144**SHOULD** use descriptive variable names:145146- `NSString *username` - clear and concise147- `NSString *accessToken` - describes the token type148- `MSALAccount *currentAccount` - not just `account`149- `MSIDRequestParameters *requestParams` - abbreviated but clear150- `MSALPublicClientApplicationConfig *config` - clear context151152**NOT RECOMMENDED:** Single letter variable names (except loop counters)153154#### Pointer Asterisks155156**MUST** attach asterisks to variable name:157158```objc159// Correct160NSString *clientId161162// Incorrect163NSString* clientId164NSString * clientId165```166167Exception: Constants (`NSString * const MSALErrorDomain`)168169#### Properties vs Instance Variables170171**SHOULD** use properties instead of naked instance variables.172173```objc174// Preferred175@interface MSALAccount : NSObject176@property (nonatomic) NSString *username;177@property (nonatomic) NSString *environment;178@end179180// Avoid181@interface MSALAccount : NSObject182{183 NSString *username;184 NSString *environment;185}186@end187```188189**SHOULD** avoid direct instance variable access except in:190191- Initializer methods (`init`, `initWithCoder:`)192- `dealloc` methods193- Custom setters and getters194195#### Variable Qualifiers196197**SHOULD** place ARC qualifiers between asterisks and variable name:198199```objc200NSString * __weak weakReference;201MSALAccount * __autoreleasing autoreleasedAccount;202```203204### 8. Naming Conventions205206#### Class Names and Constants207208**MUST** use `MSAL` prefix for public classes and constants209**MAY** use `MSID` prefix for internal/shared classes210211```objc212// Correct213static const NSTimeInterval MSALDefaultTokenRefreshInterval = 300.0;214static NSString * const MSALErrorDomain = @"MSALErrorDomain";215216// Incorrect217static const NSTimeInterval refreshInterval = 300.0;218```219220#### Properties and Local Variables221222**MUST** be camelCase with lowercase leading word.223224```objc225NSString *accessToken;226MSALAccount *currentAccount;227MSIDRequestParameters *requestParams;228```229230#### Instance Variables231232**MUST** be camelCase with lowercase leading word and underscore prefix:233234```objc235@implementation MSALPublicClientApplication236{237 BOOL _validateAuthority;238 WKWebView *_customWebview;239 NSString *_defaultKeychainGroup;240}241```242243### 9. Categories244245**MUST** prefix category methods with `msal` or `msid` to avoid collisions:246247```objc248// Correct249@interface NSArray (MSALAccessors)250- (id)msalObjectOrNilAtIndex:(NSUInteger)index;251@end252253// Incorrect - may conflict with other libraries254@interface NSArray (MSALAccessors)255- (id)objectOrNilAtIndex:(NSUInteger)index;256@end257```258259### 10. Comments260261**SHOULD** explain **why**, not what.262**MUST** keep comments up-to-date or delete them.263**NOT RECOMMENDED:** Block comments (code should be self-documenting).264265### 11. Literals266267**SHOULD** use literals for `NSString`, `NSDictionary`, `NSArray`, `NSNumber`:268269```objc270// Preferred271NSArray *scopes = @[@"user.read", @"mail.read", @"profile"];272NSDictionary *claims = @{@"id_token": @{@"auth_time": @{@"essential": @YES}}};273NSNumber *isEnabled = @YES;274NSNumber *timeout = @30;275276// Avoid277NSArray *scopes = [NSArray arrayWithObjects:@"user.read", @"mail.read", @"profile", nil];278```279280**Warning:** Never pass `nil` into array/dictionary literals - causes crash.281282### 12. Constants283284**MUST** declare as `static` constants:285286```objc287static NSString * const MSALErrorDomain = @"MSALErrorDomain";288static const CGFloat MSALDefaultTimeout = 30.0;289static const NSTimeInterval MSALTokenExpirationBuffer = 300.0;290```291292**MAY** use `#define` only when explicitly used as a macro.293294### 13. Enumerated Types295296**MUST** use `NS_ENUM()` for enumerations:297298```objc299typedef NS_ENUM(NSInteger, MSALPromptType)300{301 MSALPromptTypeDefault,302 MSALPromptTypeLogin,303 MSALPromptTypeConsent,304 MSALPromptTypeSelectAccount305};306```307308### 14. Private Properties309310**SHALL** declare private properties in class extensions in implementation file:311312```objc313// In MSALPublicClientApplication.m314@interface MSALPublicClientApplication()315{316 BOOL _validateAuthority;317 WKWebView *_customWebview;318}319320@property (nonatomic) MSALPublicClientApplicationConfig *internalConfig;321@property (nonatomic) MSIDExternalAADCacheSeeder *externalCacheSeeder;322@property (nonatomic) MSIDCacheConfig *msidCacheConfig;323324@end325```326327### 15. Singletons328329**SHOULD** use thread-safe pattern with `dispatch_once`:330331```objc332+ (instancetype)sharedInstance333{334 static id sharedInstance = nil;335 static dispatch_once_t onceToken;336 dispatch_once(&onceToken, ^{337 sharedInstance = [[[self class] alloc] init];338 });339 return sharedInstance;340}341```342343### 16. Imports344345**MUST NOT** group imports (repository convention).346347```objc348// Correct (as used in this repository)349#import "MSALPublicClientApplication+Internal.h"350#import "MSALPromptType_Internal.h"351#import "MSALError.h"352#import "MSALTelemetryApiId.h"353#import "MSIDMacTokenCache.h"354#import "MSIDLegacyTokenCacheAccessor.h"355#import "MSIDDefaultTokenCacheAccessor.h"356357// Do NOT group like this358// Frameworks359@import Foundation;360361// MSAL Core362#import "MSALPublicClientApplication.h"363```364365### 21. Protocols (Delegates)366367**SHOULD** make first parameter the object sending the message:368369```objc370// Correct371- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;372373// Incorrect374- (void)didSelectTableRowAtIndexPath:(NSIndexPath *)indexPath;375```376377### 22. Block Declarations378379**SHOULD** use clear formatting for complex blocks:380381```objc382__auto_type block = ^(MSALResult *result, NSError *msidError, id<MSIDRequestContext> context)383{384 NSError *msalError = [MSALErrorConverter msalErrorFromMsidError:msidError385 classifyErrors:YES386 msalOauth2Provider:self.msalOauth2Provider];387388 if (!completionBlock) return;389390 if (parameters.completionBlockQueue)391 {392 dispatch_async(parameters.completionBlockQueue, ^{393 completionBlock(result, msalError);394 });395 }396 else397 {398 completionBlock(result, msalError);399 }400};401```402403### 23. Xcode Project Organization404405**SHOULD** keep physical files in sync with Xcode project structure.406**SHOULD** reflect Xcode groups as filesystem folders.407**SHOULD** group code by feature, not just by type.408**SHOULD** enable "Treat Warnings as Errors" build setting.409410---411412## AI Agent-Specific Guidelines413414### When Adding New Features:4154161. **Match Existing Patterns**: Analyze similar existing code before implementing4172. **Follow MSAL Conventions**: Use `MSAL` prefix for public classes, `MSID` for internal code in CommonCore sub repository4183. **Maintain Consistency**: Match indentation, spacing, and naming in surrounding code4194. **Property-First**: Use `@property` declarations rather than instance variables4205. **Error Handling**: Always check return values, never the error variable4216. **Thread Safety**: Use `dispatch_once` for singletons, consider thread safety for shared resources4227. **Memory Management**: Follow ARC patterns, be mindful of retain cycles4238. **Nil Safety**: Never pass `nil` to array/dictionary literals4249. **Documentation**: Add header documentation for public APIs42510. **Test Coverage**: Consider how changes affect existing tests426427### When Modifying Existing Code:4284291. **Preserve Style**: Don't mix styles within a file4302. **Minimal Changes**: Change only what's necessary4313. **Update Comments**: Keep comments synchronized with code changes4324. **Deprecation**: Use proper deprecation warnings when replacing APIs4335. **Backward Compatibility**: Consider impact on existing integrations434435### Common MSAL Patterns:436437#### Error Handling Pattern438439```objc440NSError *msidError = nil;441BOOL result = [self performOperationWithError:&msidError];442443if (!result)444{445 if (error) *error = [MSALErrorConverter msalErrorFromMsidError:msidError];446 return NO;447}448```449450#### Completion Block Pattern451452```objc453__auto_type block = ^(MSALResult *result, NSError *error)454{455 // Process result456457 if (!completionBlock) return;458459 if (parameters.completionBlockQueue)460 {461 dispatch_async(parameters.completionBlockQueue, ^{462 completionBlock(result, error);463 });464 }465 else466 {467 completionBlock(result, error);468 }469};470```471472#### Logging Pattern473474```objc475MSID_LOG_WITH_CTX_PII(MSIDLogLevelInfo, context,476 @"Operation completed with account %@",477 MSID_PII_LOG_EMAIL(account.username));478```479480### Code Review Checklist:481482- [ ] Uses 4-space indentation (no tabs)483- [ ] Opening braces on new line484- [ ] All conditionals have braces485- [ ] Error handling checks return value, not error variable486- [ ] Method signatures properly spaced487- [ ] Variables descriptively named488- [ ] Pointers attached to variable names489- [ ] Uses properties instead of instance variables490- [ ] Category methods prefixed with `msal` or `msid`491- [ ] Uses `NS_ENUM` for enumerations492- [ ] Private properties in class extension493- [ ] Singletons use `dispatch_once`494- [ ] Imports not grouped (per repository style)495- [ ] Delegate methods include sender as first parameter496- [ ] No warnings or errors in build497- [ ] Follows existing MSAL/MSID patterns498499---500501## References502503- [Apple: The Objective-C Programming Language](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html)504- [Apple: Coding Guidelines for Cocoa](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html)505- [Apple: Memory Management Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html)506- [IETF RFC 2119: Key words for use in RFCs](http://tools.ietf.org/html/rfc2119)507508---509510## Repository-Specific Conventions511512### Key Differences from Standard Guidelines:5135141. **Braces on New Line**: Unlike many Objective-C style guides, this repository places opening braces on a new line5152. **No Import Grouping**: Imports are listed without grouping or comments5163. **MSAL/MSID Prefixes**: Public APIs use `MSAL`, internal/shared from CommonCore repository use `MSID`5174. **Extensive Logging**: PII-aware logging with `MSID_LOG_WITH_CTX` macros5185. **Block-based Async**: Completion handlers with queue dispatch patterns519520### Copyright Header521522All new files **MUST** include the Microsoft copyright header when added to this repository, but not when generating a new sample app:523524```objc525//------------------------------------------------------------------------------526//527// Copyright (c) Microsoft Corporation.528// All rights reserved.529//530// This code is licensed under the MIT License.531//532// Permission is hereby granted, free of charge, to any person obtaining a copy533// of this software and associated documentation files(the "Software"), to deal534// in the Software without restriction, including without limitation the rights535// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell536// copies of the Software, and to permit persons to whom the Software is537// furnished to do so, subject to the following conditions :538//539// The above copyright notice and this permission notice shall be included in540// all copies or substantial portions of the Software.541//542// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR543// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,544// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE545// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER546// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,547// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN548// THE SOFTWARE.549//550//------------------------------------------------------------------------------551```552553---554555## Notes556557This style guide is adapted specifically for AI agents working on the Microsoft Authentication Library (MSAL) for iOS and macOS. When in doubt, prioritize consistency with existing codebase patterns over strict adherence to external style guides.558
Also in AzureAD/microsoft-authentication-library-for-objc
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| AzureAD/microsoft-authentication-library-for-objc.clinerules/02-External-tenant-configuration.md · 344 | Cline rules | setupbuildteststyle+7 | 69/100 | 3 days ago | |
| AzureAD/microsoft-authentication-library-for-objcCLAUDE.md · 344 | CLAUDE.md | buildteststylearch+6 | 76/100 | 3 days ago | |
| AzureAD/microsoft-authentication-library-for-objc.clinerules/01-Workforce-tenant-configuration.md · 344 | Cline rules | setupbuildtestarch+5 | 58/100 | 3 days ago | |
| AzureAD/microsoft-authentication-library-for-objc.clinerules/03-MSAL-API-usage.md · 344 | Cline rules | styleapi | 58/100 | 3 days ago | |
| AzureAD/microsoft-authentication-library-for-objc.clinerules/05-feature-gating.md · 344 | Cline rules | stylearchdependenciesperformance+2 | 61/100 | 3 days ago | |
| AzureAD/microsoft-authentication-library-for-objc.clinerules/06-Customer-communication-guidelines.md · 344 | Cline rules | stylemonorepodo-notagent-behaviour | 51/100 | 3 days ago | |
| AzureAD/microsoft-authentication-library-for-objc.clinerules/AGENTS.md · 344 | AGENTS.md | styleapi | 48/100 | 3 days ago | |
| AzureAD/microsoft-authentication-library-for-objc.cursor/rules/ruler_cursor_instructions.mdc · 344 | Cursor rules | buildteststylearch+6 | 76/100 | 3 days ago | |
| AzureAD/microsoft-authentication-library-for-objc.github/copilot-instructions.md · 344 | Copilot instructions | setupbuildteststyle+11 | 64/100 | 3 days ago | |
| AzureAD/microsoft-authentication-library-for-objcAGENTS.md · 344 | AGENTS.md | buildteststylearch+6 | 76/100 | 3 days ago |
Diff against .clinerules/02-External-tenant-configuration.md Diff against CLAUDE.md Diff against .clinerules/01-Workforce-tenant-configuration.md Diff against .clinerules/03-MSAL-API-usage.md Diff against .clinerules/05-feature-gating.md Diff against .clinerules/06-Customer-communication-guidelines.md Diff against .clinerules/AGENTS.md Diff against .cursor/rules/ruler_cursor_instructions.mdc Diff against .github/copilot-instructions.md Diff against AGENTS.md
Similar configs
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| JCodesMore/ai-website-cloner-template.clinerules · 31k | Cline rules | buildlint-formatstylearch+3 | 97/100 | 2 days ago | |
| lepinkainen/humanlog.clinerules/project-rules.md · 0 | Cline rules | setupbuildtestlint-format+8 | 96/100 | 3 days ago | |
| BryaanF/LiantPortfolio.clinerules/project-guidelines.md · 0 | Cline rules | buildstylearchgit+2 | 96/100 | 3 days ago | |
| u9401066/zotero-keepervscode-extension/resources/repo-assets/pubmed-search-mcp/.clinerules/50-pubmed-project.md · 6 | Cline rules | testlint-formatstylearch+1 | 94/100 | 3 days ago | |
| u9401066/pubmed-search-mcp.clinerules/50-pubmed-project.md · 23 | Cline rules | testlint-formatstylearch+1 | 94/100 | 3 days ago | |
| u9401066/zotero-keeper.clinerules/50-pubmed-project.md · 6 | Cline rules | testlint-formatstylearch+1 | 94/100 | 3 days ago | |
| VaillerTeeter/HoshimiNest.clinerules/project-identity.md · 1 | Cline rules | setuparchtypesdo-not | 93/100 | yesterday | |
| blendsdk/codeops-mcp.clinerules/project.md · 0 | Cline rules | buildteststylearch+7 | 91/100 | 3 days ago |
