File: SyntaxDefinition.m

package info (click to toggle)
projectcenter.app 0.6.2%2Bgit20190606-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,968 kB
  • sloc: objc: 20,132; ansic: 1,463; makefile: 38
file content (577 lines) | stat: -rw-r--r-- 16,357 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
/*
    SyntaxDefinition.h

    Implementation of the SyntaxDefinition class for the
    ProjectManager application.

    Copyright (C) 2005  Saso Kiselkov

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#import "SyntaxDefinition.h"

#import <Foundation/NSArray.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSBundle.h>
#import <Foundation/NSValue.h>
#import <Foundation/NSScanner.h>

#import <AppKit/NSColor.h>
#import <AppKit/NSTextStorage.h>

NSDictionary * ParseSyntaxGraphics(NSDictionary * specification)
{
  NSMutableDictionary * dict = [NSMutableDictionary dictionary];
  NSString * value;

  value = [specification objectForKey: @"ForegroundColor"];
  if (value != nil)
    {
      float r, g, b, a;
      NSScanner * scanner = [NSScanner scannerWithString: value];

      if ([scanner scanFloat: &r] && [scanner scanFloat: &g] &&
          [scanner scanFloat: &b])
        {
          if ([scanner scanFloat: &a] == NO)
            {
              a = 1.0;
            }

          [dict setObject: [NSColor colorWithCalibratedRed: r
                                                     green: g
                                                      blue: b
                                                     alpha: a]
                   forKey: @"ForegroundColor"];
        }
      else
        {
          NSLog(_(@"Invalid ForegroundColor specification \"%@\" found: "
                  @"the correct format is \"r g b [a]\" where each component"
                  @"is a real number in the range of 0.0 thru 1.0 inclusive, "
                  @"specifying the red, green, blue and alpha (optional) "
                  @"components of the desired color."), value);
        }
    }

  value = [specification objectForKey: @"BackgroundColor"];
  if (value != nil)
    {
      float r, g, b, a;
      NSScanner * scanner = [NSScanner scannerWithString: value];

      if ([scanner scanFloat: &r] && [scanner scanFloat: &g] &&
          [scanner scanFloat: &b])
        {
          if ([scanner scanFloat: &a] == NO)
            {
              a = 1.0;
            }

          [dict setObject: [NSColor colorWithCalibratedRed: r
                                                     green: g
                                                      blue: b
                                                     alpha: a]
                   forKey: @"BackgroundColor"];
        }
      else
        {
          NSLog(_(@"Invalid BackgroundColor specification \"%@\" found: "
                  @"the correct format is \"r g b [a]\" where each component"
                  @"is a real number in the range of 0.0 thru 1.0 inclusive, "
                  @"specifying the red, green, blue and alpha (optional) "
                  @"components of the desired color."), value);
        }
    }

  value = [specification objectForKey: @"Bold"];
  if (value != nil)
    {
      [dict setObject: [NSNumber numberWithBool: [value boolValue]]
               forKey: @"Bold"];
    }

  value = [specification objectForKey: @"Italic"];
  if (value != nil)
    {
      [dict setObject: [NSNumber numberWithBool: [value boolValue]]
               forKey: @"Italic"];
    }

  return [[dict copy] autorelease];
}

void
MarkTextPatternBeginningCharacters(TextPattern * pattern,
                                   char * buffer, unsigned int bufSize)
{
  unichar * chars = PermissibleCharactersAtPatternBeginning(pattern);

  if (chars == (unichar *) -1)
    {
      memset(buffer, 1, 128);
    }
  else if (chars != NULL)
    {
      unsigned int i;
      unichar c;

      for (i = 0; (c = chars[i]) != 0; i++)
        {
          if (c < bufSize)
            {
              buffer[c] = 1;
            }
        }

      free(chars);
    }
}

static NSDictionary * syntaxes = nil;
static NSMutableDictionary * syntaxDefinitions = nil;

@interface SyntaxDefinition (Private)

+ (void)loadSyntaxDefinitions;

@end

@implementation SyntaxDefinition (Private)

/**
 * Loads all syntax definition files and associates them in the
 * static global variable `syntaxes' with their respective
 * file types. The syntax definitions aren't compiled yet - they
 * are left in their pure format and are compiled on a per-use
 * basis.
 */
+ (void)loadSyntaxDefinitions
{
  NSMutableDictionary *dict;
  NSArray             *filePaths;
  NSString            *filePath;
  NSEnumerator        *e;
  NSBundle            *bundle;

  // FIXME: need better algorithm to locate syntax files. This is good
  // only for a quick'n'dirty implementation
  bundle = [NSBundle bundleForClass:NSClassFromString(@"PCEditor")];
  filePaths = [bundle pathsForResourcesOfType:@"syntax" inDirectory:nil];

  dict = [NSMutableDictionary dictionary];
  e = [filePaths objectEnumerator];
  while ((filePath = [e nextObject]) != nil)
    {
      NSDictionary * syntax;


      syntax = [NSDictionary dictionaryWithContentsOfFile: filePath];
      if (syntax != nil)
        {
          NSEnumerator * ee = [[syntax objectForKey: @"FileTypes"]
            objectEnumerator];
          NSString * fileType;

          while ((fileType = [ee nextObject]) != nil)
            {
              [dict setObject: [syntax objectForKey: @"Contexts"]
                       forKey: fileType];
            }
        }
    }

  ASSIGNCOPY(syntaxes, dict);
}

@end

@implementation SyntaxDefinition

+ (void)initialize
{
  if (syntaxes == nil)
    {
      [self loadSyntaxDefinitions];
      syntaxDefinitions = [NSMutableDictionary new];
    }
}

+ syntaxDefinitionForFileType:(NSString *)fileType
                  textStorage:(NSTextStorage *)aTextStorage
{
  SyntaxDefinition * def;

  def = [syntaxDefinitions objectForKey: fileType];
  if (def == nil)
    {
      NSArray * contexts = [syntaxes objectForKey: fileType];

      if (contexts != nil)
        {
          def = [[[SyntaxDefinition alloc]
            initWithContextList: contexts
                    textStorage: aTextStorage]
            autorelease];

          if (def != nil)
            {
              [syntaxDefinitions setObject: def forKey: fileType];
            }

          return def;
        }
      else
        {
          return nil;
        }
    }
  else
    {
      return def;
    }
}

- initWithContextList:(NSArray *)contexts
          textStorage:(NSTextStorage *)aTextStorage
{
  if ([self init])
    {
      NSUInteger i, n;
      NSMutableArray * contextGraphicsTmp = [NSMutableArray array],
                     * keywordGraphicsTmp = [NSMutableArray array];

      ASSIGN(textStorage, aTextStorage);

      // compile the syntax definition
      for (i = 0, n = [contexts count]; i < n; i++)
        {
          NSUInteger j, keywordCount, skipCount;
          NSDictionary * context = [contexts objectAtIndex: i];
          NSArray * ctxtKeywords, * skips;
          NSMutableArray * contextKeywordsGraphicsTmp;

          // context beginning/ending missing?
          if (([context objectForKey: @"Beginning"] == nil ||
               [context objectForKey: @"Ending"] == nil) &&
              i > 0)
            {
              NSLog(@"Syntax compilation error: context %" PRIuPTR "  missing "
                      @"beginning or ending symbol.", i);

              [self release];
              return nil;
            }

          // process context beginnings/endings
          if (i > 0)
            {
              contextBeginnings = realloc(contextBeginnings, i *
                sizeof(TextPattern *));
              contextBeginnings[i - 1] = CompileTextPattern([context
                objectForKey: @"Beginning"]);

              MarkTextPatternBeginningCharacters(contextBeginnings[i - 1],
                contextBeginningChars, sizeof(contextBeginningChars));

              contextEndings = realloc(contextEndings, i *
                sizeof(TextPattern *));
              contextEndings[i - 1] = CompileTextPattern([context
                objectForKey: @"Ending"]);
            }

          // process context skips
          contextSkipChars = realloc(contextSkipChars, (i + 1) *
            sizeof(char *));
          contextSkipChars[i] = calloc(128, sizeof(char));
          contextSkips = realloc(contextSkips, sizeof(TextPattern **) *
            (i + 1));
          contextSkips[i] = NULL;
          skips = [context objectForKey: @"ContextSkips"];
          for (j = 0, skipCount = [skips count]; j < skipCount; j++)
            {
              NSString * skip = [skips objectAtIndex: j];

              contextSkips[i] = realloc(contextSkips[i], (j + 1) *
                sizeof(TextPattern *));
              contextSkips[i][j] = CompileTextPattern(skip);
              MarkTextPatternBeginningCharacters(contextSkips[i][j],
                contextSkipChars[i], 128);
            }
          contextSkips[i] = realloc(contextSkips[i], (j + 1) *
            sizeof(TextPattern *));
          contextSkips[i][j] = NULL;

          // process context graphics
          [contextGraphicsTmp addObject: ParseSyntaxGraphics(context)];

          keywords = realloc(keywords, (i + 1) * sizeof(TextPattern **));
          keywords[i] = NULL;

          ctxtKeywords = [context objectForKey: @"Keywords"];
          contextKeywordsGraphicsTmp = [NSMutableArray arrayWithCapacity:
            [ctxtKeywords count]];

          // run through all keywords in the context
          for (j = 0, keywordCount = [ctxtKeywords count];
               j < keywordCount;
               j++)
            {
              NSDictionary * keyword = [ctxtKeywords objectAtIndex: j];
              NSString * keywordString = [keyword objectForKey: @"Pattern"];
              TextPattern * pattern;

              if (keywordString == nil)
                {
                  NSLog(_(@"Missing keyword pattern declaration "
                          @"in context %i keyword %i. Ignoring all the "
                          @"remaining of the keywords in this context."),
                          i, j);
                  break;
                }
              pattern = CompileTextPattern(keywordString);
              if (pattern == NULL)
                {
                  break;
                }

              keywords[i] = realloc(keywords[i],
                                    (j + 1) * sizeof(TextPattern *));
              keywords[i][j] = pattern;

              [contextKeywordsGraphicsTmp addObject:
                ParseSyntaxGraphics(keyword)];
            }

          // append a trailing NULL to terminate the list
          keywords[i] = realloc(keywords[i], (j + 1) * sizeof(TextPattern *));
          keywords[i][j] = NULL;

          [keywordGraphicsTmp addObject: [[contextKeywordsGraphicsTmp
            copy] autorelease]];
        }

      // terminate the keywords array by appending a trailing NULL pointer
      keywords = realloc(keywords, (i + 1) * sizeof(TextPattern **));
      keywords[i] = NULL;

      // begining and ending arrays don't include the default context!
      // Thus it is indexed by 'i' not 'i + 1'
      contextBeginnings = realloc(contextBeginnings, i *
        sizeof(TextPattern **));
      contextBeginnings[i - 1] = NULL;
      contextEndings = realloc(contextEndings, i * sizeof(TextPattern **));
      contextEndings[i - 1] = NULL;

      contextSkipChars = realloc(contextSkipChars, (i + 1) * sizeof(char *));
      contextSkipChars[i] = NULL;

      ASSIGNCOPY(contextGraphics, contextGraphicsTmp);
      ASSIGNCOPY(keywordGraphics, keywordGraphicsTmp);

      return self;
    }
  else
    {
      return nil;
    }
}

- (void) dealloc
{
  TextPattern * pattern;
  unsigned int i;
  TextPattern ** patternList;
  char * buf;

  // free context beginnings
  for (i = 0; (pattern = contextBeginnings[i]) != NULL; i++)
    {
      FreeTextPattern(pattern);
    }
  free(contextBeginnings);

  // free context endings
  for (i = 0; (pattern = contextEndings[i]) != NULL; i++)
    {
      FreeTextPattern(pattern);
    }
  free(contextEndings);

  // free context skip characters
  for (i = 0; (buf = contextSkipChars[i]) != NULL; i++)
    {
      free(buf);
    }
  free(contextSkipChars);

  // free context skips
  for (i = 0; (patternList = contextSkips[i]) != NULL; i++)
    {
      unsigned int j;

      for (j = 0; (pattern = patternList[j]) != NULL; j++)
        {
          FreeTextPattern(pattern);
        }
      free(patternList);
    }
  free(contextSkips);

  // free keywords
  for (i = 0; (patternList = keywords[i]) != NULL; i++)
    {
      unsigned int j;

      for (j = 0; (pattern = patternList[j]) != NULL; j++)
        {
          FreeTextPattern(pattern);
        }

      free(patternList);
    }
  free(keywords);

  TEST_RELEASE(textStorage);
  TEST_RELEASE(contextGraphics);
  TEST_RELEASE(keywordGraphics);

  [super dealloc];
}

/**
 * Returns a NULL pointer terminated list of context beginning symbols.
 */
- (TextPattern **)contextBeginnings
{
  return contextBeginnings;
}

- (const char *)contextBeginningCharacters
{
  return contextBeginningChars;
}

- (unsigned int)numberOfContextBeginningCharacters
{
  return sizeof(contextBeginningChars);
}

- (const char *)contextSkipCharactersForContext:(NSUInteger)ctxt
{
  return contextSkipChars[ctxt];
}

- (unsigned int)numberOfContextSkipCharactersForContext:(NSUInteger)ctxt
{
  return 128;
}

/**
 * Returns the context ending symbol for the context identified by `ctxt'.
 */
- (TextPattern *)contextEndingForContext:(NSUInteger)ctxt
{
  return contextEndings[ctxt];
}

- (TextPattern **)contextSkipsForContext:(NSUInteger)ctxt
{
  return contextSkips[ctxt];
}

- (NSColor *)foregroundColorForContext:(NSUInteger)context
{
  return [[contextGraphics
    objectAtIndex: context]
    objectForKey: @"ForegroundColor"];
}

- (NSColor *)backgroundColorForContext:(NSUInteger)context
{
  return [[contextGraphics
    objectAtIndex: context]
    objectForKey: @"BackgroundColor"];
}

- (BOOL)isItalicFontForContext:(NSUInteger)context
{
  return [[[contextGraphics
    objectAtIndex: context]
    objectForKey: @"Italic"]
    boolValue];
}

- (BOOL)isBoldFontForContext:(NSUInteger)context
{
  return [[[contextGraphics
    objectAtIndex: context]
    objectForKey: @"Bold"]
    boolValue];
}

/**
 * Returns a NULL pointer terminated list of text patterns representing
 * keywords to be matched inside context `context'.
 */
- (TextPattern **)keywordsInContext:(NSUInteger)context
{
  return keywords[context];
}

/**
 * Returns the color with which the keyword identified by `keyword'
 * in `contextName' should be colored. The argument `keyword' is the
 * index of the keyword in the array returned by -keywordsInContext:.
 */
- (NSColor *)foregroundColorForKeyword:(NSUInteger)keyword
			     inContext:(NSUInteger)context
{
  return [[[keywordGraphics objectAtIndex:context]
			    objectAtIndex:keyword]
			     objectForKey:@"ForegroundColor"];
}

- (NSColor *)backgroundColorForKeyword:(NSUInteger)keyword
			     inContext:(NSUInteger)context
{
  return [[[keywordGraphics objectAtIndex:context]
			    objectAtIndex:keyword]
			     objectForKey:@"BackgroundColor"];
}
- (BOOL)isItalicFontForKeyword:(NSUInteger)keyword
		     inContext:(NSUInteger)context
{
  return [[[[keywordGraphics objectAtIndex:context]
			     objectAtIndex:keyword]
			      objectForKey:@"Italic"]
			      boolValue];
}

/**
 * Returns YES if the font with which the keyword identified by `keyword'
 * should be bold and NO if it should be normal weigth.
 */
- (BOOL)isBoldFontForKeyword:(NSUInteger)keyword
       		   inContext:(NSUInteger)context
{
  return [[[[keywordGraphics objectAtIndex:context]
			     objectAtIndex:keyword]
			      objectForKey:@"Bold"]
			      boolValue];
}

@end