Oolite
Loading...
Searching...
No Matches
OOStringExpander.m
Go to the documentation of this file.
1/*
2
3OOStringExpander.m
4
5
6Oolite
7Copyright (C) 2004-2013 Giles C Williams and contributors
8
9This program is free software; you can redistribute it and/or
10modify it under the terms of the GNU General Public License
11as published by the Free Software Foundation; either version 2
12of the License, or (at your option) any later version.
13
14This program is distributed in the hope that it will be useful,
15but WITHOUT ANY WARRANTY; without even the impllied warranty of
16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17GNU General Public License for more details.
18
19You should have received a copy of the GNU General Public License
20along with this program; if not, write to the Free Software
21Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22MA 02110-1301, USA.
23
24*/
25
26#import "OOStringExpander.h"
28#import "OOFoundation.h"
29#import "OOJavaScriptEngine.h"
30#import "OOStringParsing.h"
31#import "PlayerEntity.h"
33#import "ResourceManager.h"
34#import "Universe.h"
35
36// Syntax warnings are for OXP developers, so include them wherever the debug console is.
37#if OOLITE_DEBUG || defined(OO_DEBUG_MONITOR_ENABLED)
38#define WARNINGS 1
39#else
40#define WARNINGS 0
41#endif
42
43#define OO_EXPANDER_RANDOM (context->useGoodRNG ? (Ranrot() & 0xFF) : gen_rnd_number())
44
45enum {
46 /*
47 Total stack limit for strings being parsed (in UTF-16 code elements,
48 i.e. units of 2 bytes), used recursively - for instance, if the root
49 string takes 10,000 characters, any string it recurses into gets
50 kStackAllocationLimit - 10,000. If the limit would be exceeded,
51 the unexpanded string is returned instead.
52
53 The limit is expected to be much higher than necessary for any practical
54 string, and exists only to catch pathological behaviour without crashing.
55 */
57
58 /*
59 Recursion limit, for much the same purpose. Without it, we crash about
60 22,000 stack frames deep when trying to expand a = "[a]" on a Mac.
61 */
63};
64
65/* OOStringExpansionContext
66
67 Struct used to store context and caches for the entire string expansion
68 operation, including recursive calls (so it can't contain anything pertaining
69 to the specific string being expanded).
70*/
71typedef struct
72{
74 NSString* systemName;
75 NSDictionary* overrides;
76 NSDictionary* legacyLocals;
79 bool hasPercentR; // Set to indicate we need an ExpandPercentR() pass.
82
83 NSString* systemNameWithIan; // Cache for %I
84 NSString* randomNameN; // Cache for %N
85 NSString* randomNameR; // Cache for %R
86 NSArray* systemDescriptions; // Cache for system_description, used for numbered keys.
87 NSUInteger sysDescCount; // Count of systemDescriptions, valid after GetSystemDescriptions() called.
89
90/* Accessors for lazily-instantiated caches in context.
91 */
92static NSString* GetSystemName(OOStringExpansionContext* context); // %H
93static NSString* GetSystemNameIan(OOStringExpansionContext* context); // %I
94static NSString* GetRandomNameN(OOStringExpansionContext* context); // %N
95static NSString* GetRandomNameR(OOStringExpansionContext* context); // %R
96static NSArray* GetSystemDescriptions(OOStringExpansionContext* context);
97
98static void AppendCharacters(NSMutableString** result, const unichar* characters, NSUInteger start, NSUInteger end);
99
100static NSString* NewRandomDigrams(OOStringExpansionContext* context);
101static NSString* OldRandomDigrams(void);
102
103// Various bits of expansion logic, each with a comment of its very own at the implementation.
104static NSString* Expand(OOStringExpansionContext* context, NSString* string, NSUInteger sizeLimit, NSUInteger recursionLimit);
105
106static NSString* ExpandKey(OOStringExpansionContext* context, const unichar* characters, NSUInteger size, NSUInteger idx, NSUInteger* replaceLength, NSUInteger sizeLimit, NSUInteger recursionLimit);
107static NSString* ExpandDigitKey(OOStringExpansionContext* context, const unichar* characters, NSUInteger keyStart, NSUInteger keyLength, NSUInteger sizeLimit, NSUInteger recursionLimit);
108static NSString* ExpandStringKey(OOStringExpansionContext* context, NSString* key, NSUInteger sizeLimit, NSUInteger recursionLimit);
109static NSString* ExpandStringKeyOverride(OOStringExpansionContext* context, NSString* key);
110static NSString* ExpandStringKeySpecial(OOStringExpansionContext* context, NSString* key);
111static NSString* ExpandStringKeyKeyboardBinding(OOStringExpansionContext* context, NSString* key);
112static NSMapTable* SpecialSubstitutionSelectors(void);
113static NSString* ExpandStringKeyFromDescriptions(OOStringExpansionContext* context, NSString* key, NSUInteger sizeLimit, NSUInteger recursionLimit);
114static NSString* ExpandStringKeyMissionVariable(OOStringExpansionContext* context, NSString* key);
115static NSString* ExpandStringKeyLegacyLocalVariable(OOStringExpansionContext* context, NSString* key);
116static NSString* ExpandLegacyScriptSelectorKey(OOStringExpansionContext* context, NSString* key);
117static SEL LookUpLegacySelector(NSString* key);
118
119static NSString* ExpandPercentEscape(OOStringExpansionContext* context, const unichar* characters, NSUInteger size, NSUInteger idx, NSUInteger* replaceLength);
120static NSString* ExpandSystemNameForGalaxyEscape(OOStringExpansionContext* context, const unichar* characters, NSUInteger size, NSUInteger idx, NSUInteger* replaceLength);
121static NSString* ExpandSystemNameEscape(OOStringExpansionContext* context, const unichar* characters, NSUInteger size, NSUInteger idx, NSUInteger* replaceLength);
122static NSString* ExpandPercentR(OOStringExpansionContext* context, NSString* input);
123#if WARNINGS
124static void ReportWarningForUnknownKey(OOStringExpansionContext* context, NSString* key);
125#endif
126
127static NSString* ApplyOperators(NSString* string, NSString* operatorsString);
128static NSString* ApplyOneOperator(NSString* string, NSString* op, NSString* param);
129
130/* SyntaxWarning(context, logMessageClass, format, ...)
131 SyntaxError(context, logMessageClass, format, ...)
132
133 Report warning or error for expansion syntax, including unknown keys.
134
135 Warnings are reported as JS warnings or log messages (depending on the
136 context->isJavaScript flag) if the relevant log message class is enabled.
137 Warnings are completely disabled in Deployment builds.
138
139 Errors are reported as JS warnings (not exceptions) or log messages (again
140 depending on context->isJavaScript) in all configurations. Exceptions are
141 not used to avoid breaking code that worked with the old expander, even if
142 it was questionable.
143
144 Errors that are not syntax or invalid keys are reported with OOLogERR().
145*/
146static void SyntaxIssue(OOStringExpansionContext* context, const char* function, const char* fileName, NSUInteger line, NSString* logMessageClass, NSString* prefix, NSString* format, ...) OO_TAKES_FORMAT_STRING(7, 8);
147#define SyntaxError(CONTEXT, CLASS, FORMAT, ...) SyntaxIssue(CONTEXT, OOLOG_FUNCTION_NAME, OOLOG_FILE_NAME, __LINE__, CLASS, OOLOG_WARNING_PREFIX, FORMAT, ##__VA_ARGS__)
148
149#if WARNINGS
150#define SyntaxWarning(CONTEXT, CLASS, FORMAT, ...) SyntaxIssue(CONTEXT, OOLOG_FUNCTION_NAME, OOLOG_FILE_NAME, __LINE__, CLASS, OOLOG_WARNING_PREFIX, FORMAT, ##__VA_ARGS__)
151#else
152#define SyntaxWarning(...) \
153 do { \
154 } while (0)
155#endif
156
157// MARK: -
158// MARK: Public functions
159
160NSString* OOExpandDescriptionString(Random_Seed seed, NSString* string, NSDictionary* overrides, NSDictionary* legacyLocals, NSString* systemName, OOExpandOptions options)
161{
162 if (string == nil)
163 return nil;
164
165 OOStringExpansionContext context = {
166 .seed = seed,
167 .systemName = [systemName retain],
168 .overrides = [overrides retain],
169 .legacyLocals = [legacyLocals retain],
170 .isJavaScript = options & kOOExpandForJavaScript,
171 .convertBackslashN = options & kOOExpandBackslashN,
172 .useGoodRNG = options & kOOExpandGoodRNG
173 };
174
175 // Avoid recursive %I expansion by pre-seeding cache with literal %I.
176 if (options & kOOExpandDisallowPercentI) {
177 context.systemNameWithIan = @"%I";
178 }
179
180 OORandomState savedRandomState;
181 if (options & kOOExpandReseedRNG) {
182 savedRandomState = OOSaveRandomState();
184 }
185
186 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
187 NSString *result = nil, *intermediate = nil;
188 @try {
189 // TODO: profile caching the results. Would need to keep track of whether we've done something nondeterministic (array selection, %R etc).
190 if (options & kOOExpandKey) {
191 intermediate = ExpandStringKey(&context, string, kStackAllocationLimit, kRecursionLimit);
192 } else {
193 intermediate = Expand(&context, string, kStackAllocationLimit, kRecursionLimit);
194 }
195 if (!context.hasPercentR) {
196 result = intermediate;
197 } else {
198 result = ExpandPercentR(&context, intermediate);
199 }
200 }
201 @finally {
202 [context.systemName release];
203 [context.overrides release];
204 [context.legacyLocals release];
205 [context.systemNameWithIan release];
206 [context.randomNameN release];
207 [context.randomNameR release];
208 [context.systemDescriptions release];
209 }
210
211 if (options & kOOExpandReseedRNG) {
212 OORestoreRandomState(savedRandomState);
213 }
214
215 result = [result copy];
216 [pool release];
217 return [result autorelease];
218}
219
220NSString* OOGenerateSystemDescription(Random_Seed seed, NSString* name)
221{
223 return OOExpandDescriptionString(seed, @"system-description-string", nil, nil, name, kOOExpandKey);
224}
225
227{
228 return [[UNIVERSE systemManager] getRandomSeedForCurrentSystem];
229}
230
231// MARK: -
232// MARK: Guts
233
234/* Expand(context, string, sizeLimit, recursionLimit)
235
236 Top-level expander. Expands all types of substitution in a string.
237
238 <sizeLimit> is the remaining budget for stack allocation of read buffers.
239 (Expand() is the only function that creates such buffers.) <recursionLimit>
240 limits the number of recursive calls of Expand() that are permitted. If one
241 of the limits would be exceeded, Expand() returns the input string unmodified.
242*/
243static NSString* Expand(OOStringExpansionContext* context, NSString* string, NSUInteger sizeLimit, NSUInteger recursionLimit)
244{
245 NSCParameterAssert(string != nil && context != NULL && sizeLimit <= kStackAllocationLimit);
246
247 const NSUInteger size = [string length];
248
249 // Avoid stack overflow.
250 if (EXPECT_NOT(size > sizeLimit || recursionLimit == 0))
251 return string;
252 sizeLimit -= size;
253 recursionLimit--;
254
255 // Nothing to expand in an empty string, and the size-1 thing below would be trouble.
256 if (size == 0)
257 return string;
258
259 unichar characters[size];
260 [string getCharacters:characters range:(NSRange) { 0, size }];
261
262 /* Beginning of current range of non-special characters. If we encounter
263 a substitution, we'll be copying from here forward.
264 */
265 NSUInteger copyRangeStart = 0;
266
267 // Mutable string for result if we perform any substitutions.
268 NSMutableString* result = nil;
269
270 /* The iteration limit is size - 1 because every valid substitution is at
271 least 2 characters long. This way, characters[idx + 1] is always valid.
272 */
273 for (NSUInteger idx = 0; idx < size - 1; idx++) {
274 /* Main parsing loop. If, at the end of the loop, replacement != nil,
275 we copy the characters from copyRangeStart to idx into the result,
276 the insert replacement, and skip replaceLength characters forward
277 (minus one, because idx is incremented by the loop.)
278 */
279 NSString* replacement = nil;
280 NSUInteger replaceLength = 0;
281 unichar thisChar = characters[idx];
282
283 if (thisChar == '[') {
284 replacement = ExpandKey(context, characters, size, idx, &replaceLength, sizeLimit, recursionLimit);
285 } else if (thisChar == '%') {
286 replacement = ExpandPercentEscape(context, characters, size, idx, &replaceLength);
287 } else if (thisChar == ']') {
288 SyntaxWarning(context, @"strings.expand.warning.unbalancedClosingBracket", @"%@", @"Unbalanced ] in string.");
289 } else if (thisChar == '\\' && context->convertBackslashN) {
290 if (characters[idx + 1] == 'n') {
291 replaceLength = 2;
292 replacement = @"\n";
293 }
294 } else {
295 // No token start character, so we definitely have no replacement.
296 continue;
297 }
298
299 if (replacement != nil) {
300 /* If replacement string is "\x7F", eat the following character.
301 This is used in system_description for the one empty string
302 in [22].
303 */
304 if ([replacement isEqualToString:@"\x7F"] && replaceLength < size) {
305 replaceLength++;
306 replacement = @"";
307 }
308
309 // Avoid copying if we're replacing the entire input string.
310 if (copyRangeStart == 0 && replaceLength == size) {
311 return replacement;
312 }
313
314 // Write the pending literal segment to result. This also allocates result if needed.
315 AppendCharacters(&result, characters, copyRangeStart, idx);
316
317 [result appendString:replacement];
318
319 // Skip over replaced part and start a new literal segment.
320 idx += replaceLength - 1;
321 copyRangeStart = idx + 1;
322 }
323 }
324
325 if (result != nil) {
326 // Append any trailing literal segment.
327 AppendCharacters(&result, characters, copyRangeStart, size);
328
329 // Don't turn result immutable; doing it once at top level is sufficient.
330 return result;
331 } else {
332 // No substitutions, return original string.
333 return string;
334 }
335}
336
337/* ExpandKey(context, characters, size, idx, replaceLength, sizeLimit, recursionLimit)
338
339 Expand a substitution key, i.e. a section surrounded by square brackets.
340 On entry, <idx> is the offset to an opening bracket. ExpandKey() searches
341 for the balancing closing bracket, and if it is found dispatches to either
342 ExpandDigitKey() (for a key consisting only of digits) or ExpandStringKey()
343 (for anything else).
344
345 The key may be terminated by a vertical bar |, followed by an operator. An
346 operator is an identifier, optionally followed by a colon and additional
347 text, and may be terminated with another bar and operator.
348*/
349static NSString* ExpandKey(OOStringExpansionContext* context, const unichar* characters, NSUInteger size, NSUInteger idx, NSUInteger* replaceLength, NSUInteger sizeLimit, NSUInteger recursionLimit)
350{
351 NSCParameterAssert(context != NULL && characters != NULL && replaceLength != NULL);
352 NSCParameterAssert(characters[idx] == '[');
353
354 // Find the balancing close bracket.
355 NSUInteger end, balanceCount = 1, firstBar = 0;
356 bool allDigits = true;
357
358 for (end = idx + 1; end < size && balanceCount > 0; end++) {
359 if (characters[end] == ']')
360 balanceCount--;
361 else {
362 if (characters[end] == '[')
363 balanceCount++;
364 else if (characters[end] == '|' && firstBar == 0)
365 firstBar = end;
366 if (!isdigit(characters[end]) && firstBar == 0)
367 allDigits = false;
368 }
369 }
370
371 // Fail if no balancing bracket.
372 if (EXPECT_NOT(balanceCount != 0)) {
373 SyntaxWarning(context, @"strings.expand.warning.unbalancedOpeningBracket", @"%@", @"Unbalanced [ in string.");
374 return nil;
375 }
376
377 NSUInteger totalLength = end - idx;
378 *replaceLength = totalLength;
379 NSUInteger keyStart = idx + 1, keyLength = totalLength - 2;
380 if (firstBar != 0)
381 keyLength = firstBar - idx - 1;
382
383 if (EXPECT_NOT(keyLength == 0)) {
384 SyntaxWarning(context, @"strings.expand.warning.emptyKey", @"%@", @"Invalid expansion code [] string. (To avoid this message, use %%[%%].)");
385 return nil;
386 }
387
388 NSString* expanded = nil;
389 if (allDigits) {
390 expanded = ExpandDigitKey(context, characters, keyStart, keyLength, sizeLimit, recursionLimit);
391 } else {
392 NSString* key = [NSString stringWithCharacters:characters + keyStart length:keyLength];
393 expanded = ExpandStringKey(context, key, sizeLimit, recursionLimit);
394 }
395
396 if (firstBar != 0) {
397 NSString* operators = [NSString stringWithCharacters:characters + firstBar + 1 length:end - firstBar - 2];
398 expanded = ApplyOperators(expanded, operators);
399 }
400
401 return expanded;
402}
403
404/* ApplyOperators(string, operatorsString)
405
406 Given a string and a series of formatting operators separated by vertical
407 bars (or a single formatting operator), apply the operators, in sequence,
408 to the string.
409 */
410static NSString* ApplyOperators(NSString* string, NSString* operatorsString)
411{
412 NSArray* operators = [operatorsString componentsSeparatedByString:@"|"];
413 NSString* op = nil;
414
415 foreach (op, operators) {
416 NSString* param = nil;
417 NSRange colon = [op rangeOfString:@":"];
418 if (colon.location != NSNotFound) {
419 param = [op substringFromIndex:colon.location + colon.length];
420 op = [op substringToIndex:colon.location];
421 }
422 string = ApplyOneOperator(string, op, param);
423 }
424
425 return string;
426}
427
428static NSString* Operator_cr(NSString* string, NSString* param)
429{
430 return OOCredits([string doubleValue] * 10);
431}
432
433static NSString* Operator_dcr(NSString* string, NSString* param)
434{
435 return OOCredits([string longLongValue]);
436}
437
438static NSString* Operator_icr(NSString* string, NSString* param)
439{
440 return OOIntCredits([string longLongValue]);
441}
442
443static NSString* Operator_idcr(NSString* string, NSString* param)
444{
445 return OOIntCredits(round([string doubleValue] / 10.0));
446}
447
448static NSString* Operator_precision(NSString* string, NSString* param)
449{
450 return [NSString stringWithFormat:@"%.*f", [param intValue], [string doubleValue]];
451}
452
453static NSString* Operator_multiply(NSString* string, NSString* param)
454{
455 return [NSString stringWithFormat:@"%g", [string doubleValue] * [param doubleValue]];
456}
457
458static NSString* Operator_add(NSString* string, NSString* param)
459{
460 return [NSString stringWithFormat:@"%g", [string doubleValue] + [param doubleValue]];
461}
462
463/* ApplyOneOperator(string, op, param)
464
465 Apply a single formatting operator to a string.
466
467 For example, the expansion expression "[distance|precision:1]" will be
468 expanded by a call to ApplyOneOperator(@"distance", @"precision", @"1").
469
470 <param> may be nil, indicating an operator with no parameter (no colon).
471 */
472static NSString* ApplyOneOperator(NSString* string, NSString* op, NSString* param)
473{
474 static NSDictionary* operators = nil;
475
476 if (operators == nil) {
477#define OPERATOR(name) [NSValue valueWithPointer:Operator_##name], @ #name
478 operators = [[NSDictionary alloc] initWithObjectsAndKeys:
479 OPERATOR(dcr),
480 OPERATOR(cr),
481 OPERATOR(icr),
482 OPERATOR(idcr),
483 OPERATOR(precision),
484 OPERATOR(multiply),
485 OPERATOR(add),
486 nil];
487 }
488
489 NSString* (*operator)(NSString* string, NSString* param) = [[operators objectForKey:op] pointerValue];
490 if (operator!= NULL) {
491 return operator(string, param);
492 }
493
494 OOLogERR(@"strings.expand.invalidOperator", @"Unknown string expansion operator %@", op);
495 return string;
496}
497
498/* ExpandDigitKey(context, characters, keyStart, keyLength, sizeLimit, recursionLimit)
499
500 Expand a key (as per ExpandKey()) consisting entirely of digits. <keyStart>
501 and <keyLength> specify the range of characters containing the key.
502
503 Digit-only keys are looked up in the system_description array in
504 descriptions.plist, which is expected to contain only arrays of strings (no
505 loose strings). When an array is retrieved, a string is selected from it
506 at random and the result is expanded recursively by calling Expand().
507*/
508static NSString* ExpandDigitKey(OOStringExpansionContext* context, const unichar* characters, NSUInteger keyStart, NSUInteger keyLength, NSUInteger sizeLimit, NSUInteger recursionLimit)
509{
510 NSCParameterAssert(context != NULL && characters != NULL);
511
512 NSUInteger keyValue = 0, idx;
513 for (idx = keyStart; idx < (keyStart + keyLength); idx++) {
514 NSCAssert2(isdigit(characters[idx]), @"%s called with non-numeric key [%@].", __FUNCTION__, [NSString stringWithCharacters:characters + keyStart length:keyLength]);
515
516 keyValue = keyValue * 10 + characters[idx] - '0';
517 }
518
519 // Retrieve selected system_description entry.
520 NSArray* sysDescs = GetSystemDescriptions(context);
521 NSArray* entry = [sysDescs oo_arrayAtIndex:keyValue];
522
523 if (EXPECT_NOT(entry == nil)) {
524 if (keyValue >= context->sysDescCount) {
525 SyntaxWarning(context, @"strings.expand.warning.outOfRangeKey", @"Out-of-range system description expansion key [%@] in string.", [NSString stringWithCharacters:characters + keyStart length:keyLength]);
526 } else {
527 // This is out of the scope of whatever triggered it, so shouldn't be a JS warning.
528 OOLogERR(@"strings.expand.invalidData", @"%@", @"descriptions.plist entry system_description must be an array of arrays of strings.");
529 }
530 return nil;
531 }
532
533 // Select a random sub-entry.
534 NSUInteger selection, count = [entry count];
535 NSUInteger rnd = OO_EXPANDER_RANDOM;
536 if (count == 5 && !context->useGoodRNG) {
537 // Time-honoured Elite-compatible way for five items.
538 if (rnd >= 0xCC)
539 selection = 4;
540 else if (rnd >= 0x99)
541 selection = 3;
542 else if (rnd >= 0x66)
543 selection = 2;
544 else if (rnd >= 0x33)
545 selection = 1;
546 else
547 selection = 0;
548 } else {
549 // General way.
550 selection = (rnd * count) / 256;
551 }
552
553 // Look up and recursively expand string.
554 NSString* string = [entry oo_stringAtIndex:selection];
555 return Expand(context, string, sizeLimit, recursionLimit);
556}
557
558/* ExpandStringKey(context, key, sizeLimit, recursionLimit)
559
560 Expand a key (as per ExpandKey()) which doesn't consist entirely of digits.
561 Looks for the key in a number of different places in prioritized order.
562*/
563static NSString* ExpandStringKey(OOStringExpansionContext* context, NSString* key, NSUInteger sizeLimit, NSUInteger recursionLimit)
564{
565 NSCParameterAssert(context != NULL && key != nil);
566
567 // Overrides have top priority.
568 NSString* result = ExpandStringKeyOverride(context, key);
569
570 // Specials override descriptions.plist.
571 if (result == nil)
572 result = ExpandStringKeySpecial(context, key);
573
574 // Now try descriptions.plist.
575 if (result == nil)
576 result = ExpandStringKeyFromDescriptions(context, key, sizeLimit, recursionLimit);
577
578 // For efficiency, descriptions.plist overrides keybindings.
579 // OXPers should therefore avoid oolite_key_ description keys
580 if (result == nil)
581 result = ExpandStringKeyKeyboardBinding(context, key);
582
583 // Try mission variables.
584 if (result == nil)
585 result = ExpandStringKeyMissionVariable(context, key);
586
587 // Try legacy local variables.
588 if (result == nil)
589 result = ExpandStringKeyLegacyLocalVariable(context, key);
590
591 // Try legacy script methods.
592 if (result == nil)
593 ExpandLegacyScriptSelectorKey(context, key);
594
595#if WARNINGS
596 // None of that worked, so moan a bit.
597 if (result == nil)
598 ReportWarningForUnknownKey(context, key);
599#endif
600
601 return result;
602}
603
604/* ExpandStringKeyOverride(context, key)
605
606 Attempt to expand a key by retriving it from the overrides dictionary of
607 the context (ultimately from OOExpandDescriptionString()). Overrides are
608 used to provide context-specific expansions, such as "[self:name]" in
609 comms messages, and can also be used from JavaScript.
610
611 The main difference between overrides and legacy locals is priority.
612*/
613static NSString* ExpandStringKeyOverride(OOStringExpansionContext* context, NSString* key)
614{
615 NSCParameterAssert(context != NULL && key != nil);
616
617 id value = [context->overrides objectForKey:key];
618 if (value != nil) {
619#if WARNINGS
620 if (![value isKindOfClass:[NSString class]] && ![value isKindOfClass:[NSNumber class]]) {
621 SyntaxWarning(context, @"strings.expand.warning.invalidOverride", @"String expansion override value %@ for [%@] is not a string or number.", [value shortDescription], key);
622 }
623#endif
624 return [value description];
625 }
626
627 return nil;
628}
629
630/* ExpandStringKeySpecial(context, key)
631
632 Attempt to expand a key by matching a set of special expansion codes that
633 call PlayerEntity methods but aren't legacy script methods. Also unlike
634 legacy script methods, all these methods return strings.
635*/
636static NSString* ExpandStringKeySpecial(OOStringExpansionContext* context, NSString* key)
637{
638 NSCParameterAssert(context != NULL && key != nil);
639
640 NSMapTable* specials = SpecialSubstitutionSelectors();
641 SEL selector = NSMapGet(specials, key);
642 if (selector != NULL) {
643 NSCAssert2([PLAYER respondsToSelector:selector], @"Special string expansion selector %@ for [%@] is not implemented.", NSStringFromSelector(selector), key);
644
645 NSString* result = [PLAYER performSelector:selector];
646 if (result != nil) {
647 NSCAssert2([result isKindOfClass:[NSString class]], @"Special string expansion [%@] expanded to %@, but expected a string.", key, [result shortDescription]);
648 return result;
649 }
650 }
651
652 return nil;
653}
654
655/* ExpandStringKeyKeyboardBinding(context, key)
656
657 Attempt to expand a key by matching it against the keybindings
658*/
659static NSString* ExpandStringKeyKeyboardBinding(OOStringExpansionContext* context, NSString* key)
660{
661 NSCParameterAssert(context != NULL && key != nil);
662 if ([key hasPrefix:@"oolite_key_"]) {
663 NSString* binding = [key substringFromIndex:7];
664 return [PLAYER keyBindingDescription2:binding];
665 }
666 return nil;
667}
668
669/* SpecialSubstitutionSelectors()
670
671 Retrieve the mapping of special keys for ExpandStringKeySpecial() to
672 selectors.
673*/
674static NSMapTable* SpecialSubstitutionSelectors(void)
675{
676 static NSMapTable* specials = NULL;
677 if (specials != NULL)
678 return specials;
679
680 struct {
681 NSString* key;
682 SEL selector;
683 } selectors[] = {
684 { @"commander_name", @selector(commanderName_string) },
685 { @"commander_shipname", @selector(commanderShip_string) },
686 { @"commander_shipdisplayname", @selector(commanderShipDisplayName_string) },
687 { @"commander_rank", @selector(commanderRank_string) },
688 { @"commander_kills", @selector(commanderKillsAsString) },
689 { @"commander_legal_status", @selector(commanderLegalStatus_string) },
690 { @"commander_bounty", @selector(commanderBountyAsString) },
691 { @"credits_number", @selector(creditsFormattedForSubstitution) },
692 { @"_oo_legacy_credits_number", @selector(creditsFormattedForLegacySubstitution) }
693 };
694 unsigned i, count = sizeof selectors / sizeof *selectors;
695
696 specials = NSCreateMapTable(NSObjectMapKeyCallBacks, NSNonOwnedPointerMapValueCallBacks, count);
697 for (i = 0; i < count; i++) {
698 NSMapInsertKnownAbsent(specials, selectors[i].key, selectors[i].selector);
699 }
700
701 return specials;
702}
703
704/* ExpandStringKeyFromDescriptions(context, key, sizeLimit, recursionLimit)
705
706 Attempt to expand a key by looking it up in descriptions.plist. Matches
707 may be single strings or arrays of strings. For arrays, one of the strings
708 is selected at random.
709
710 Matched strings are expanded recursively by calling Expand().
711*/
712static NSString* ExpandStringKeyFromDescriptions(OOStringExpansionContext* context, NSString* key, NSUInteger sizeLimit, NSUInteger recursionLimit)
713{
714 id value = [[UNIVERSE descriptions] objectForKey:key];
715 if (value != nil) {
716 if ([value isKindOfClass:[NSArray class]] && [value count] > 0) {
717 NSUInteger rnd = OO_EXPANDER_RANDOM % [value count];
718 value = [value oo_objectAtIndex:rnd];
719 }
720
721 if (![value isKindOfClass:[NSString class]]) {
722 // This is out of the scope of whatever triggered it, so shouldn't be a JS warning.
723 OOLogERR(@"strings.expand.invalidData", @"String expansion value %@ for [%@] from descriptions.plist is not a string or number.", [value shortDescription], key);
724 return nil;
725 }
726
727 // Expand recursively.
728 return Expand(context, value, sizeLimit, recursionLimit);
729 }
730
731 return nil;
732}
733
734/* ExpandStringKeyMissionVariable(context, key)
735
736 Attempt to expand a key by matching it to a mission variable.
737*/
738static NSString* ExpandStringKeyMissionVariable(OOStringExpansionContext* context, NSString* key)
739{
740 if ([key hasPrefix:@"mission_"]) {
741 return [PLAYER missionVariableForKey:key];
742 }
743
744 return nil;
745}
746
747/* ExpandStringKeyMissionVariable(context, key)
748
749 Attempt to expand a key by matching it to a legacy local variable.
750
751 The main difference between overrides and legacy locals is priority.
752*/
753static NSString* ExpandStringKeyLegacyLocalVariable(OOStringExpansionContext* context, NSString* key)
754{
755 return [[context->legacyLocals objectForKey:key] description];
756}
757
758/* ExpandLegacyScriptSelectorKey(context, key)
759
760 Attempt to expand a key by treating it as a legacy script query method and
761 invoking it. Only whitelisted methods are permitted, and aliases are
762 respected.
763*/
764static NSString* ExpandLegacyScriptSelectorKey(OOStringExpansionContext* context, NSString* key)
765{
766 NSCParameterAssert(context != NULL && key != nil);
767
768 SEL selector = LookUpLegacySelector(key);
769
770 if (selector != NULL) {
771 return [[PLAYER performSelector:selector] description];
772 } else {
773 return nil;
774 }
775}
776
777/* LookUpLegacySelector(key)
778
779 If <key> is a whitelisted legacy script query method, or aliases to one,
780 return the corresponding selector.
781*/
782static SEL LookUpLegacySelector(NSString* key)
783{
784 SEL selector = NULL;
785 static NSMapTable* selectorCache = NULL;
786
787 // Try cache lookup.
788 if (selectorCache != NULL) {
789 selector = NSMapGet(selectorCache, key);
790 }
791
792 if (selector == NULL) {
793 static NSDictionary* aliases = nil;
794 static NSSet* whitelist = nil;
795 if (whitelist == nil) {
796 NSDictionary* whitelistDict = [ResourceManager whitelistDictionary];
797 whitelist = [[NSSet alloc] initWithArray:[whitelistDict oo_arrayForKey:@"query_methods"]];
798 aliases = [[whitelistDict oo_dictionaryForKey:@"query_method_aliases"] copy];
799 }
800
801 NSString* selectorName = [aliases oo_stringForKey:key];
802 if (selectorName == nil)
803 selectorName = key;
804
805 if ([whitelist containsObject:selectorName]) {
806 selector = NSSelectorFromString(selectorName);
807
808 /* This is an assertion, not a warning, because whitelist.plist is
809 part of the game and cannot be overriden by OXPs. If there is an
810 invalid selector in the whitelist, it's a game bug.
811 */
812 NSCAssert1([PLAYER respondsToSelector:selector], @"Player does not respond to whitelisted query selector %@.", key);
813 }
814
815 if (selector != NULL) {
816 // Add it to cache.
817 if (selectorCache == NULL) {
818 selectorCache = NSCreateMapTable(NSObjectMapKeyCallBacks, NSNonOwnedPointerMapValueCallBacks, [whitelist count]);
819 }
820 NSMapInsertKnownAbsent(selectorCache, key, selector);
821 }
822 }
823
824 return selector;
825}
826
827#if WARNINGS
828/* ReportWarningForUnknownKey(context, key)
829
830 Called when we fall through all the various ways of expanding string keys
831 above. If the key looks like a legacy script query method, assume it is
832 and report a bad selector. Otherwise, report it as an unknown key.
833*/
834static void ReportWarningForUnknownKey(OOStringExpansionContext* context, NSString* key)
835{
836 if ([key hasSuffix:@"_string"] || [key hasSuffix:@"_number"] || [key hasSuffix:@"_bool"]) {
837 SyntaxError(context, @"strings.expand.invalidSelector", @"Unpermitted legacy script method [%@] in string.", key);
838 } else {
839 SyntaxWarning(context, @"strings.expand.warning.unknownExpansion", @"Unknown expansion key [%@] in string.", key);
840 }
841}
842#endif
843
844/* ExpandKey(context, characters, size, idx, replaceLength)
845
846 Expand an escape code. <idx> is the index of the % sign introducing the
847 escape code. Supported escape codes are:
848 %H
849 %I
850 %N
851 %R
852 %J###, where ### are three digits
853 %G######, where ### are six digits
854 %%
855 %[
856 %]
857
858 In addition, the codes %@, %d and %. are ignored, because they're used
859 with -[NSString stringWithFormat:] on strings that have already been
860 expanded.
861
862 Any other code results in a warning.
863*/
864static NSString* ExpandPercentEscape(OOStringExpansionContext* context, const unichar* characters, NSUInteger size, NSUInteger idx, NSUInteger* replaceLength)
865{
866 NSCParameterAssert(context != NULL && characters != NULL && replaceLength != NULL);
867 NSCParameterAssert(characters[idx] == '%');
868
869 // All %-escapes except %J and %G are 2 characters.
870 *replaceLength = 2;
871 unichar selector = characters[idx + 1];
872
873 switch (selector) {
874 case 'H':
875 return GetSystemName(context);
876
877 case 'I':
878 return GetSystemNameIan(context);
879
880 case 'N':
881 return GetRandomNameN(context);
882
883 case 'R':
884 // to keep planet description generation consistent with earlier versions
885 // this must be done after all other substitutions in a second pass.
886 context->hasPercentR = true;
887 return @"%R";
888
889 case 'G':
890 return ExpandSystemNameForGalaxyEscape(context, characters, size, idx, replaceLength);
891
892 case 'J':
893 return ExpandSystemNameEscape(context, characters, size, idx, replaceLength);
894
895 case '%':
896 return @"%";
897
898 case '[':
899 return @"[";
900
901 case ']':
902 return @"]";
903
904 /* These are NSString formatting specifiers that occur in
905 descriptions.plist. The '.' is for floating-point (g and f)
906 specifiers that have field widths specified. No unadorned
907 %f or %g is found in vanilla Oolite descriptions.plist.
908
909 Ideally, these would be replaced with the caller formatting
910 the value and passing it as an override - it would be safer
911 and make descriptions.plist clearer - but it would be a big
912 job and uglify the callers without newfangled Objective-C
913 dictionary literals.
914 -- Ahruman 2012-10-05
915 */
916 case '@':
917 case 'd':
918 case '.':
919 return nil;
920
921 default:
922 // Yay, percent signs!
923 SyntaxWarning(context, @"strings.expand.warning.unknownPercentEscape", @"Unknown escape code in string: %%%lc. (To encode a %% sign without this warning, use %%%% - but prefer \"percent\" in prose writing.)", selector);
924
925 return nil;
926 }
927}
928
929/* ExpandPercentR(context, string)
930 Replaces all %R in string with its expansion.
931 Separate to allow this to be delayed to the end of the string expansion
932 for compatibility with 1.76 expansion of %R in planet descriptions
933*/
934static NSString* ExpandPercentR(OOStringExpansionContext* context, NSString* input)
935{
936 NSRange containsR = [input rangeOfString:@"%R"];
937 if (containsR.location == NSNotFound) {
938 return input; // no %Rs to replace
939 }
940 NSString* percentR = GetRandomNameR(context);
941 NSMutableString* output = [NSMutableString stringWithString:input];
942
943 /* This loop should be completely unnecessary, but for some reason
944 * replaceOccurrencesOfString sometimes only replaces the first
945 * instance of %R if percentR contains the non-ASCII
946 * digrams-apostrophe character. (I guess
947 * http://lists.gnu.org/archive/html/gnustep-dev/2011-10/msg00048.html
948 * this bug in GNUstep's implementation here, which is in 1.22) So
949 * to cover that case, if there are still %R in the string after
950 * replacement, try again. Affects things like thargoid curses, and
951 * particularly %Rful expansions of [nom]. Probably this can be
952 * tidied up once GNUstep 1.22 is ancient history, but that'll be a
953 * few years yet. - CIM 15/1/2013 */
954
955 do {
956 [output replaceOccurrencesOfString:@"%R" withString:percentR options:NSLiteralSearch range:NSMakeRange(0, [output length])];
957 } while ([output rangeOfString:@"%R"].location != NSNotFound);
958
959 return [NSString stringWithString:output];
960}
961
962/* ExpandSystemNameForGalaxyEscape(context, characters, size, idx, replaceLength)
963
964 Expand a %G###### code by looking up the corresponding system name in any
965 cgalaxy.
966*/
967static NSString* ExpandSystemNameForGalaxyEscape(OOStringExpansionContext* context, const unichar* characters, NSUInteger size, NSUInteger idx, NSUInteger* replaceLength)
968{
969 NSCParameterAssert(context != NULL && characters != NULL && replaceLength != NULL);
970 NSCParameterAssert(characters[idx + 1] == 'G');
971
972 // A valid %G escape is always eight characters including the six digits.
973 *replaceLength = 8;
974
975#define kInvalidGEscapeMessage @"String escape code %G must be followed by six integers."
976 if (EXPECT_NOT(size - idx < 8)) {
977 // Too close to end of string to actually have six characters, let alone six digits.
978 SyntaxError(context, @"strings.expand.invalidJEscape", @"%@", kInvalidGEscapeMessage);
979 return nil;
980 }
981
982 char hundreds = characters[idx + 2];
983 char tens = characters[idx + 3];
984 char units = characters[idx + 4];
985 char galHundreds = characters[idx + 5];
986 char galTens = characters[idx + 6];
987 char galUnits = characters[idx + 7];
988
989 if (!(isdigit(hundreds) && isdigit(tens) && isdigit(units) && isdigit(galHundreds) && isdigit(galTens) && isdigit(galUnits))) {
990 SyntaxError(context, @"strings.expand.invalidJEscape", @"%@", kInvalidGEscapeMessage);
991 return nil;
992 }
993
994 OOSystemID sysID = (hundreds - '0') * 100 + (tens - '0') * 10 + (units - '0');
995 if (sysID > kOOMaximumSystemID) {
996 SyntaxError(context, @"strings.expand.invalidJEscape.range", @"String escape code %%G%3u for system is out of range (must be less than %u).", sysID, kOOMaximumSystemID + 1);
997 return nil;
998 }
999
1000 OOGalaxyID galID = (galHundreds - '0') * 100 + (galTens - '0') * 10 + (galUnits - '0');
1001 if (galID > kOOMaximumGalaxyID) {
1002 SyntaxError(context, @"strings.expand.invalidJEscape.range", @"String escape code %%G%3u for galaxy is out of range (must be less than %u).", galID, kOOMaximumGalaxyID + 1);
1003 return nil;
1004 }
1005
1006 return [UNIVERSE getSystemName:sysID forGalaxy:galID];
1007}
1008
1009/* ExpandSystemNameEscape(context, characters, size, idx, replaceLength)
1010
1011 Expand a %J### code by looking up the corresponding system name in the
1012 current galaxy.
1013*/
1014static NSString* ExpandSystemNameEscape(OOStringExpansionContext* context, const unichar* characters, NSUInteger size, NSUInteger idx, NSUInteger* replaceLength)
1015{
1016 NSCParameterAssert(context != NULL && characters != NULL && replaceLength != NULL);
1017 NSCParameterAssert(characters[idx + 1] == 'J');
1018
1019 // A valid %J escape is always five characters including the three digits.
1020 *replaceLength = 5;
1021
1022#define kInvalidJEscapeMessage @"String escape code %J must be followed by three integers."
1023 if (EXPECT_NOT(size - idx < 5)) {
1024 // Too close to end of string to actually have three characters, let alone three digits.
1025 SyntaxError(context, @"strings.expand.invalidJEscape", @"%@", kInvalidJEscapeMessage);
1026 return nil;
1027 }
1028
1029 char hundreds = characters[idx + 2];
1030 char tens = characters[idx + 3];
1031 char units = characters[idx + 4];
1032
1033 if (!(isdigit(hundreds) && isdigit(tens) && isdigit(units))) {
1034 SyntaxError(context, @"strings.expand.invalidJEscape", @"%@", kInvalidJEscapeMessage);
1035 return nil;
1036 }
1037
1038 OOSystemID sysID = (hundreds - '0') * 100 + (tens - '0') * 10 + (units - '0');
1039 if (sysID > kOOMaximumSystemID) {
1040 SyntaxError(context, @"strings.expand.invalidJEscape.range", @"String escape code %%J%3u is out of range (must be less than %u).", sysID, kOOMaximumSystemID + 1);
1041 return nil;
1042 }
1043
1044 return [UNIVERSE getSystemName:sysID];
1045}
1046
1047static void AppendCharacters(NSMutableString** result, const unichar* characters, NSUInteger start, NSUInteger end)
1048{
1049 NSCParameterAssert(result != NULL && characters != NULL && start <= end);
1050
1051 if (*result == nil) {
1052 // Ensure there is a string. We want this even if the range is empty.
1053 *result = [NSMutableString string];
1054 }
1055
1056 if (start == end)
1057 return;
1058
1059 /* What we want here is a method like -[NSMutableString
1060 appendCharacters:(unichar)characters length:(NSUInteger)length], which
1061 unfortunately doesn't exist. On Mac OS X, CoreFoundation provides an
1062 equivalent. For GNUstep, we have to use a temporary string.
1063
1064 TODO: build the output string in a fixed-size stack buffer instead.
1065 */
1066#if OOLITE_MAC_OS_X
1067 CFStringAppendCharacters((CFMutableStringRef)*result, characters + start, end - start);
1068#else
1069 NSString* temp = [[NSString alloc] initWithCharacters:characters + start length:end - start];
1070 [*result appendString:temp];
1071 [temp release];
1072#endif
1073}
1074
1075static NSString* GetSystemName(OOStringExpansionContext* context)
1076{
1077 NSCParameterAssert(context != NULL);
1078 if (context->systemName == nil) {
1079 context->systemName = [[UNIVERSE getSystemName:[PLAYER systemID]] retain];
1080 }
1081
1082 return context->systemName;
1083}
1084
1086{
1087 NSCParameterAssert(context != NULL);
1088
1089 if (context->systemNameWithIan == nil) {
1090 context->systemNameWithIan = [OOExpandWithOptions(context->seed, kOOExpandDisallowPercentI | kOOExpandGoodRNG | kOOExpandKey, @"planetname-possessive") retain];
1091 }
1092
1093 return context->systemNameWithIan;
1094}
1095
1097{
1098 NSCParameterAssert(context != NULL);
1099
1100 if (context->randomNameN == nil) {
1101 context->randomNameN = [NewRandomDigrams(context) retain];
1102 }
1103
1104 return context->randomNameN;
1105}
1106
1108{
1109 NSCParameterAssert(context != NULL);
1110
1111 if (context->randomNameR == nil) {
1112 context->randomNameR = [OldRandomDigrams() retain];
1113 }
1114
1115 return context->randomNameR;
1116}
1117
1119{
1120 NSCParameterAssert(context != NULL);
1121
1122 if (context->systemDescriptions == nil) {
1123 context->systemDescriptions = [[[UNIVERSE descriptions] oo_arrayForKey:@"system_description"] retain];
1124 context->sysDescCount = [context->systemDescriptions count];
1125 }
1126
1127 return context->systemDescriptions;
1128}
1129
1130/* Generates pseudo-random digram string using gen_rnd_number()
1131 (world-generation consistent PRNG), but misses some possibilities. Used
1132 for "%R" description string for backwards compatibility.
1133*/
1134static NSString* OldRandomDigrams(void)
1135{
1136 /* The only point of using %R is for world generation, so there's
1137 * no point in checking the context */
1138 unsigned len = gen_rnd_number() & 3;
1139 NSString* digrams = [[UNIVERSE descriptions] objectForKey:@"digrams"];
1140 NSMutableString* name = [NSMutableString stringWithCapacity:256];
1141
1142 for (unsigned i = 0; i <= len; i++) {
1143 unsigned x = gen_rnd_number() & 0x3e;
1144 [name appendString:[digrams substringWithRange:NSMakeRange(x, 2)]];
1145 }
1146
1147 return [name capitalizedString];
1148}
1149
1150/* Generates pseudo-random digram string. Used for "%N" description string.
1151 */
1153{
1154 unsigned length = (OO_EXPANDER_RANDOM % 4) + 1;
1155 if ((OO_EXPANDER_RANDOM % 5) < ((length == 1) ? 3 : 1))
1156 ++length; // Make two-letter names rarer and 10-letter names happen sometimes
1157 NSString* digrams = [[UNIVERSE descriptions] objectForKey:@"digrams"];
1158 NSUInteger count = [digrams length] / 2;
1159 NSMutableString* name = [NSMutableString stringWithCapacity:length * 2];
1160
1161 for (unsigned i = 0; i != length; ++i) {
1162 [name appendString:[digrams substringWithRange:NSMakeRange((OO_EXPANDER_RANDOM % count) * 2, 2)]];
1163 }
1164
1165 return [name capitalizedString];
1166}
1167
1168static void SyntaxIssue(OOStringExpansionContext* context, const char* function, const char* fileName, NSUInteger line, NSString* logMessageClass, NSString* prefix, NSString* format, ...)
1169{
1170 NSCParameterAssert(context != NULL);
1171
1172 va_list args;
1173 va_start(args, format);
1174
1175 if (OOLogWillDisplayMessagesInClass(logMessageClass)) {
1176 if (context->isJavaScript) {
1177 /* NOTE: syntax errors are reported as warnings when called from JS
1178 because we don't want to start throwing exceptions when the old
1179 expander didn't.
1180 */
1181 JSContext* jsc = OOJSAcquireContext();
1182 OOJSReportWarningWithArguments(jsc, format, args);
1184 } else {
1185 format = [prefix stringByAppendingString:format];
1186 OOLogWithFunctionFileAndLineAndArguments(logMessageClass, function, fileName, line, format, args);
1187 }
1188 }
1189
1190 va_end(args);
1191}
#define EXPECT_NOT(x)
#define OO_TAKES_FORMAT_STRING(stringIndex, firstToCheck)
void OOJSReportWarningWithArguments(JSContext *context, NSString *format, va_list args)
OOINLINE JSContext * OOJSAcquireContext(void)
OOINLINE void OOJSRelinquishContext(JSContext *context)
#define OOLogERR(class, format,...)
Definition OOLogging.h:125
void void void OOLogWithFunctionFileAndLineAndArguments(NSString *inMessageClass, const char *inFunction, const char *inFile, unsigned long inLine, NSString *inFormat, va_list inArguments) OO_TAKES_FORMAT_STRING(5
BOOL OOLogWillDisplayMessagesInClass(NSString *inMessageClass)
Definition OOLogging.m:136
unsigned count
return nil
float x
NSUInteger OOExpandOptions
@ kOOExpandForJavaScript
Report warnings through JavaScript runtime system instead of normal logging.
@ kOOExpandDisallowPercentI
Disallow I expansion (used when expanding I itself).
@ kOOExpandKey
Treat string as a key. Expand("foo", kOOExpandKey) == Expand(@"[foo]", kOOExpandNoOptions).
@ kOOExpandBackslashN
Convert literal "\\n"s to line breaks (used for missiontext.plist for historical reasons).
@ kOOExpandGoodRNG
Use RANDROT for selecting from description arrays and for N expansion.
@ kOOExpandReseedRNG
Set "really random" seeds while expanding.
static void SyntaxIssue(OOStringExpansionContext *context, const char *function, const char *fileName, NSUInteger line, NSString *logMessageClass, NSString *prefix, NSString *format,...) OO_TAKES_FORMAT_STRING(7
NSString * OOGenerateSystemDescription(Random_Seed seed, NSString *name)
static NSString * ExpandStringKeyLegacyLocalVariable(OOStringExpansionContext *context, NSString *key)
static NSString * GetSystemName(OOStringExpansionContext *context)
#define kInvalidGEscapeMessage
static NSString * Operator_icr(NSString *string, NSString *param)
#define SyntaxError(CONTEXT, CLASS, FORMAT,...)
static NSString * ExpandStringKeyFromDescriptions(OOStringExpansionContext *context, NSString *key, NSUInteger sizeLimit, NSUInteger recursionLimit)
static NSArray * GetSystemDescriptions(OOStringExpansionContext *context)
#define OO_EXPANDER_RANDOM
static NSString * Expand(OOStringExpansionContext *context, NSString *string, NSUInteger sizeLimit, NSUInteger recursionLimit)
static NSString * ExpandDigitKey(OOStringExpansionContext *context, const unichar *characters, NSUInteger keyStart, NSUInteger keyLength, NSUInteger sizeLimit, NSUInteger recursionLimit)
Random_Seed OOStringExpanderDefaultRandomSeed(void)
static NSString * ExpandLegacyScriptSelectorKey(OOStringExpansionContext *context, NSString *key)
static NSString * ApplyOperators(NSString *string, NSString *operatorsString)
static NSString * ExpandSystemNameEscape(OOStringExpansionContext *context, const unichar *characters, NSUInteger size, NSUInteger idx, NSUInteger *replaceLength)
static NSString * ExpandStringKeyMissionVariable(OOStringExpansionContext *context, NSString *key)
#define SyntaxWarning(CONTEXT, CLASS, FORMAT,...)
static NSString * Operator_dcr(NSString *string, NSString *param)
static NSString * GetSystemNameIan(OOStringExpansionContext *context)
static NSString * ExpandStringKeyOverride(OOStringExpansionContext *context, NSString *key)
static NSString * OldRandomDigrams(void)
static NSString * Operator_cr(NSString *string, NSString *param)
#define kInvalidJEscapeMessage
static NSString * Operator_precision(NSString *string, NSString *param)
static NSString * ExpandStringKey(OOStringExpansionContext *context, NSString *key, NSUInteger sizeLimit, NSUInteger recursionLimit)
static SEL LookUpLegacySelector(NSString *key)
static NSString * ExpandPercentEscape(OOStringExpansionContext *context, const unichar *characters, NSUInteger size, NSUInteger idx, NSUInteger *replaceLength)
static NSString * GetRandomNameR(OOStringExpansionContext *context)
static NSString * Operator_multiply(NSString *string, NSString *param)
@ kRecursionLimit
@ kStackAllocationLimit
static NSString * ExpandSystemNameForGalaxyEscape(OOStringExpansionContext *context, const unichar *characters, NSUInteger size, NSUInteger idx, NSUInteger *replaceLength)
static NSString * NewRandomDigrams(OOStringExpansionContext *context)
NSString * OOExpandDescriptionString(Random_Seed seed, NSString *string, NSDictionary *overrides, NSDictionary *legacyLocals, NSString *systemName, OOExpandOptions options)
static void ReportWarningForUnknownKey(OOStringExpansionContext *context, NSString *key)
static NSString * ApplyOneOperator(NSString *string, NSString *op, NSString *param)
static NSString * ExpandStringKeyKeyboardBinding(OOStringExpansionContext *context, NSString *key)
static void AppendCharacters(NSMutableString **result, const unichar *characters, NSUInteger start, NSUInteger end)
static NSString * ExpandStringKeySpecial(OOStringExpansionContext *context, NSString *key)
static NSMapTable * SpecialSubstitutionSelectors(void)
static NSString * Operator_idcr(NSString *string, NSString *param)
static NSString * ExpandKey(OOStringExpansionContext *context, const unichar *characters, NSUInteger size, NSUInteger idx, NSUInteger *replaceLength, NSUInteger sizeLimit, NSUInteger recursionLimit)
static NSString * GetRandomNameN(OOStringExpansionContext *context)
static NSString * ExpandPercentR(OOStringExpansionContext *context, NSString *input)
static NSString * Operator_add(NSString *string, NSString *param)
OOINLINE NSString * OOCredits(OOCreditsQuantity tenthsOfCredits)
OOINLINE NSString * OOIntCredits(OOCreditsQuantity integerCredits)
@ kOOMaximumSystemID
Definition OOTypes.h:187
@ kOOMaximumGalaxyID
Definition OOTypes.h:186
int16_t OOSystemID
Definition OOTypes.h:183
uint8_t OOGalaxyID
Definition OOTypes.h:182
#define PLAYER
NSDictionary * whitelistDictionary()
voidpf void uLong size
Definition ioapi.h:126
void seed_RNG_only_for_planet_description(Random_Seed s_seed)
void OORestoreRandomState(OORandomState state)
OORandomState OOSaveRandomState(void)
int gen_rnd_number(void)
void OOSetReallyRandomRANROTAndRndSeeds(void)