forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsCSSScanner.cpp
1416 lines (1278 loc) · 37.1 KB
/
nsCSSScanner.cpp
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* tokenization of CSS style sheets */
#include <math.h> // must be first due to symbol conflicts
#include "nsCSSScanner.h"
#include "nsString.h"
#include "nsCRT.h"
#include "mozilla/Util.h"
// for #ifdef CSS_REPORT_PARSE_ERRORS
#include "nsCOMPtr.h"
#include "nsIServiceManager.h"
#include "nsIComponentManager.h"
#include "nsReadableUtils.h"
#include "nsIURI.h"
#include "nsIConsoleService.h"
#include "nsIScriptError.h"
#include "nsIStringBundle.h"
#include "nsIDocument.h"
#include "mozilla/Services.h"
#include "mozilla/css/Loader.h"
#include "nsCSSStyleSheet.h"
#include "mozilla/Preferences.h"
using namespace mozilla;
#ifdef CSS_REPORT_PARSE_ERRORS
static bool gReportErrors = true;
static nsIConsoleService *gConsoleService;
static nsIFactory *gScriptErrorFactory;
static nsIStringBundle *gStringBundle;
#endif
static const PRUint8 IS_HEX_DIGIT = 0x01;
static const PRUint8 START_IDENT = 0x02;
static const PRUint8 IS_IDENT = 0x04;
static const PRUint8 IS_WHITESPACE = 0x08;
static const PRUint8 IS_URL_CHAR = 0x10;
#define W IS_WHITESPACE
#define I IS_IDENT
#define U IS_URL_CHAR
#define S START_IDENT
#define UI IS_IDENT |IS_URL_CHAR
#define USI IS_IDENT|START_IDENT |IS_URL_CHAR
#define UXI IS_IDENT |IS_HEX_DIGIT|IS_URL_CHAR
#define UXSI IS_IDENT|START_IDENT|IS_HEX_DIGIT|IS_URL_CHAR
static const PRUint8 gLexTable[] = {
// TAB LF FF CR
0, 0, 0, 0, 0, 0, 0, 0, 0, W, W, 0, W, W, 0, 0,
//
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// SPC ! " # $ % & ' ( ) * + , - . /
W, U, 0, U, U, U, U, 0, 0, 0, U, U, U, UI, U, U,
// 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
UXI,UXI,UXI,UXI,UXI,UXI,UXI,UXI,UXI,UXI,U, U, U, U, U, U,
// @ A B C D E F G H I J K L M N O
U,UXSI,UXSI,UXSI,UXSI,UXSI,UXSI,USI,USI,USI,USI,USI,USI,USI,USI,USI,
// P Q R S T U V W X Y Z [ \ ] ^ _
USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,U, S, U, U, USI,
// ` a b c d e f g h i j k l m n o
U,UXSI,UXSI,UXSI,UXSI,UXSI,UXSI,USI,USI,USI,USI,USI,USI,USI,USI,USI,
// p q r s t u v w x y z { | } ~
USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,U, U, U, U, 0,
// U+008*
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// U+009*
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// U+00A*
USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,
// U+00B*
USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,
// U+00C*
USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,
// U+00D*
USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,
// U+00E*
USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,
// U+00F*
USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI,USI
};
MOZ_STATIC_ASSERT(NS_ARRAY_LENGTH(gLexTable) == 256,
"gLexTable expected to cover all 2^8 possible PRUint8s");
#undef W
#undef S
#undef I
#undef U
#undef UI
#undef USI
#undef UXI
#undef UXSI
static inline bool
IsIdentStart(PRInt32 aChar)
{
return aChar >= 0 &&
(aChar >= 256 || (gLexTable[aChar] & START_IDENT) != 0);
}
static inline bool
StartsIdent(PRInt32 aFirstChar, PRInt32 aSecondChar)
{
return IsIdentStart(aFirstChar) ||
(aFirstChar == '-' && IsIdentStart(aSecondChar));
}
static inline bool
IsWhitespace(PRInt32 ch) {
return PRUint32(ch) < 256 && (gLexTable[ch] & IS_WHITESPACE) != 0;
}
static inline bool
IsDigit(PRInt32 ch) {
return (ch >= '0') && (ch <= '9');
}
static inline bool
IsHexDigit(PRInt32 ch) {
return PRUint32(ch) < 256 && (gLexTable[ch] & IS_HEX_DIGIT) != 0;
}
static inline bool
IsIdent(PRInt32 ch) {
return ch >= 0 && (ch >= 256 || (gLexTable[ch] & IS_IDENT) != 0);
}
static inline bool
IsURLChar(PRInt32 ch) {
return ch >= 0 && (ch >= 256 || (gLexTable[ch] & IS_URL_CHAR) != 0);
}
static inline PRUint32
DecimalDigitValue(PRInt32 ch)
{
return ch - '0';
}
static inline PRUint32
HexDigitValue(PRInt32 ch)
{
if (IsDigit(ch)) {
return DecimalDigitValue(ch);
} else {
// Note: c&7 just keeps the low three bits which causes
// upper and lower case alphabetics to both yield their
// "relative to 10" value for computing the hex value.
return (ch & 0x7) + 9;
}
}
nsCSSToken::nsCSSToken()
{
mType = eCSSToken_Symbol;
}
void
nsCSSToken::AppendToString(nsString& aBuffer)
{
switch (mType) {
case eCSSToken_AtKeyword:
aBuffer.Append(PRUnichar('@')); // fall through intentional
case eCSSToken_Ident:
case eCSSToken_WhiteSpace:
case eCSSToken_Function:
case eCSSToken_HTMLComment:
case eCSSToken_URange:
aBuffer.Append(mIdent);
if (mType == eCSSToken_Function)
aBuffer.Append(PRUnichar('('));
break;
case eCSSToken_URL:
case eCSSToken_Bad_URL:
aBuffer.AppendLiteral("url(");
if (mSymbol != PRUnichar(0)) {
aBuffer.Append(mSymbol);
}
aBuffer.Append(mIdent);
if (mSymbol != PRUnichar(0)) {
aBuffer.Append(mSymbol);
}
if (mType == eCSSToken_URL) {
aBuffer.Append(PRUnichar(')'));
}
break;
case eCSSToken_Number:
if (mIntegerValid) {
aBuffer.AppendInt(mInteger, 10);
}
else {
aBuffer.AppendFloat(mNumber);
}
break;
case eCSSToken_Percentage:
NS_ASSERTION(!mIntegerValid, "How did a percentage token get this set?");
aBuffer.AppendFloat(mNumber * 100.0f);
aBuffer.Append(PRUnichar('%'));
break;
case eCSSToken_Dimension:
if (mIntegerValid) {
aBuffer.AppendInt(mInteger, 10);
}
else {
aBuffer.AppendFloat(mNumber);
}
aBuffer.Append(mIdent);
break;
case eCSSToken_String:
aBuffer.Append(mSymbol);
aBuffer.Append(mIdent); // fall through intentional
case eCSSToken_Symbol:
aBuffer.Append(mSymbol);
break;
case eCSSToken_ID:
case eCSSToken_Ref:
aBuffer.Append(PRUnichar('#'));
aBuffer.Append(mIdent);
break;
case eCSSToken_Includes:
aBuffer.AppendLiteral("~=");
break;
case eCSSToken_Dashmatch:
aBuffer.AppendLiteral("|=");
break;
case eCSSToken_Beginsmatch:
aBuffer.AppendLiteral("^=");
break;
case eCSSToken_Endsmatch:
aBuffer.AppendLiteral("$=");
break;
case eCSSToken_Containsmatch:
aBuffer.AppendLiteral("*=");
break;
case eCSSToken_Bad_String:
aBuffer.Append(mSymbol);
aBuffer.Append(mIdent);
break;
default:
NS_ERROR("invalid token type");
break;
}
}
nsCSSScanner::nsCSSScanner()
: mReadPointer(nsnull)
, mSVGMode(false)
#ifdef CSS_REPORT_PARSE_ERRORS
, mError(mErrorBuf, ArrayLength(mErrorBuf), 0)
, mInnerWindowID(0)
, mWindowIDCached(false)
, mSheet(nsnull)
, mLoader(nsnull)
#endif
{
MOZ_COUNT_CTOR(nsCSSScanner);
mPushback = mLocalPushback;
mPushbackSize = ArrayLength(mLocalPushback);
// No need to init the other members, since they represent state
// which can get cleared. We'll init them every time Init() is
// called.
}
nsCSSScanner::~nsCSSScanner()
{
MOZ_COUNT_DTOR(nsCSSScanner);
Close();
if (mLocalPushback != mPushback) {
delete [] mPushback;
}
}
#ifdef CSS_REPORT_PARSE_ERRORS
#define CSS_ERRORS_PREF "layout.css.report_errors"
static int
CSSErrorsPrefChanged(const char *aPref, void *aClosure)
{
gReportErrors = Preferences::GetBool(CSS_ERRORS_PREF, true);
return NS_OK;
}
#endif
/* static */ bool
nsCSSScanner::InitGlobals()
{
#ifdef CSS_REPORT_PARSE_ERRORS
if (gConsoleService && gScriptErrorFactory)
return true;
nsresult rv = CallGetService(NS_CONSOLESERVICE_CONTRACTID, &gConsoleService);
NS_ENSURE_SUCCESS(rv, false);
rv = CallGetClassObject(NS_SCRIPTERROR_CONTRACTID, &gScriptErrorFactory);
NS_ENSURE_SUCCESS(rv, false);
NS_ASSERTION(gConsoleService && gScriptErrorFactory,
"unexpected null pointer without failure");
Preferences::RegisterCallback(CSSErrorsPrefChanged, CSS_ERRORS_PREF);
CSSErrorsPrefChanged(CSS_ERRORS_PREF, nsnull);
#endif
return true;
}
/* static */ void
nsCSSScanner::ReleaseGlobals()
{
#ifdef CSS_REPORT_PARSE_ERRORS
Preferences::UnregisterCallback(CSSErrorsPrefChanged, CSS_ERRORS_PREF);
NS_IF_RELEASE(gConsoleService);
NS_IF_RELEASE(gScriptErrorFactory);
NS_IF_RELEASE(gStringBundle);
#endif
}
void
nsCSSScanner::Init(const nsAString& aBuffer,
nsIURI* aURI, PRUint32 aLineNumber,
nsCSSStyleSheet* aSheet, mozilla::css::Loader* aLoader)
{
NS_PRECONDITION(!mReadPointer, "Should not have an existing input buffer!");
mReadPointer = aBuffer.BeginReading();
mCount = aBuffer.Length();
#ifdef CSS_REPORT_PARSE_ERRORS
// If aURI is the same as mURI, no need to reget mFileName -- it
// shouldn't have changed.
if (aURI != mURI) {
mURI = aURI;
if (aURI) {
aURI->GetSpec(mFileName);
} else {
mFileName.Adopt(NS_strdup("from DOM"));
}
}
#endif // CSS_REPORT_PARSE_ERRORS
mLineNumber = aLineNumber;
// Reset variables that we use to keep track of our progress through the input
mOffset = 0;
mPushbackCount = 0;
#ifdef CSS_REPORT_PARSE_ERRORS
mColNumber = 0;
mSheet = aSheet;
mLoader = aLoader;
#endif
}
#ifdef CSS_REPORT_PARSE_ERRORS
// @see REPORT_UNEXPECTED_EOF in nsCSSParser.cpp
#define REPORT_UNEXPECTED_EOF(lf_) \
ReportUnexpectedEOF(#lf_)
void
nsCSSScanner::AddToError(const nsSubstring& aErrorText)
{
if (mError.IsEmpty()) {
mErrorLineNumber = mLineNumber;
mErrorColNumber = mColNumber;
mError = aErrorText;
} else {
mError.Append(NS_LITERAL_STRING(" ") + aErrorText);
}
}
void
nsCSSScanner::ClearError()
{
mError.Truncate();
}
void
nsCSSScanner::OutputError()
{
if (mError.IsEmpty()) return;
// Log it to the Error console
if (InitGlobals() && gReportErrors) {
if (!mWindowIDCached) {
if (mSheet) {
mInnerWindowID = mSheet->FindOwningWindowInnerID();
}
if (mInnerWindowID == 0 && mLoader) {
nsIDocument* doc = mLoader->GetDocument();
if (doc) {
mInnerWindowID = doc->InnerWindowID();
}
}
mWindowIDCached = true;
}
nsresult rv;
nsCOMPtr<nsIScriptError> errorObject =
do_CreateInstance(gScriptErrorFactory, &rv);
if (NS_SUCCEEDED(rv)) {
rv = errorObject->InitWithWindowID(mError.get(),
NS_ConvertUTF8toUTF16(mFileName).get(),
EmptyString().get(),
mErrorLineNumber,
mErrorColNumber,
nsIScriptError::warningFlag,
"CSS Parser",
mInnerWindowID);
if (NS_SUCCEEDED(rv)) {
gConsoleService->LogMessage(errorObject);
}
}
}
ClearError();
}
static bool
InitStringBundle()
{
if (gStringBundle)
return true;
nsCOMPtr<nsIStringBundleService> sbs =
mozilla::services::GetStringBundleService();
if (!sbs)
return false;
nsresult rv =
sbs->CreateBundle("chrome://global/locale/css.properties", &gStringBundle);
if (NS_FAILED(rv)) {
gStringBundle = nsnull;
return false;
}
return true;
}
#define ENSURE_STRINGBUNDLE \
PR_BEGIN_MACRO if (!InitStringBundle()) return; PR_END_MACRO
// aMessage must take no parameters
void nsCSSScanner::ReportUnexpected(const char* aMessage)
{
ENSURE_STRINGBUNDLE;
nsXPIDLString str;
gStringBundle->GetStringFromName(NS_ConvertASCIItoUTF16(aMessage).get(),
getter_Copies(str));
AddToError(str);
}
void
nsCSSScanner::ReportUnexpectedParams(const char* aMessage,
const PRUnichar **aParams,
PRUint32 aParamsLength)
{
NS_PRECONDITION(aParamsLength > 0, "use the non-params version");
ENSURE_STRINGBUNDLE;
nsXPIDLString str;
gStringBundle->FormatStringFromName(NS_ConvertASCIItoUTF16(aMessage).get(),
aParams, aParamsLength,
getter_Copies(str));
AddToError(str);
}
// aLookingFor is a plain string, not a format string
void
nsCSSScanner::ReportUnexpectedEOF(const char* aLookingFor)
{
ENSURE_STRINGBUNDLE;
nsXPIDLString innerStr;
gStringBundle->GetStringFromName(NS_ConvertASCIItoUTF16(aLookingFor).get(),
getter_Copies(innerStr));
const PRUnichar *params[] = {
innerStr.get()
};
nsXPIDLString str;
gStringBundle->FormatStringFromName(NS_LITERAL_STRING("PEUnexpEOF2").get(),
params, ArrayLength(params),
getter_Copies(str));
AddToError(str);
}
// aLookingFor is a single character
void
nsCSSScanner::ReportUnexpectedEOF(PRUnichar aLookingFor)
{
ENSURE_STRINGBUNDLE;
const PRUnichar lookingForStr[] = {
PRUnichar('\''), aLookingFor, PRUnichar('\''), PRUnichar(0)
};
const PRUnichar *params[] = { lookingForStr };
nsXPIDLString str;
gStringBundle->FormatStringFromName(NS_LITERAL_STRING("PEUnexpEOF2").get(),
params, ArrayLength(params),
getter_Copies(str));
AddToError(str);
}
// aMessage must take 1 parameter (for the string representation of the
// unexpected token)
void
nsCSSScanner::ReportUnexpectedToken(nsCSSToken& tok,
const char *aMessage)
{
ENSURE_STRINGBUNDLE;
nsAutoString tokenString;
tok.AppendToString(tokenString);
const PRUnichar *params[] = {
tokenString.get()
};
ReportUnexpectedParams(aMessage, params);
}
// aParams's first entry must be null, and we'll fill in the token
void
nsCSSScanner::ReportUnexpectedTokenParams(nsCSSToken& tok,
const char* aMessage,
const PRUnichar **aParams,
PRUint32 aParamsLength)
{
NS_PRECONDITION(aParamsLength > 1, "use the non-params version");
NS_PRECONDITION(aParams[0] == nsnull, "first param should be empty");
ENSURE_STRINGBUNDLE;
nsAutoString tokenString;
tok.AppendToString(tokenString);
aParams[0] = tokenString.get();
ReportUnexpectedParams(aMessage, aParams, aParamsLength);
}
#else
#define REPORT_UNEXPECTED_EOF(lf_)
#endif // CSS_REPORT_PARSE_ERRORS
void
nsCSSScanner::Close()
{
mReadPointer = nsnull;
// Clean things up so we don't hold on to memory if our parser gets recycled.
#ifdef CSS_REPORT_PARSE_ERRORS
mFileName.Truncate();
mURI = nsnull;
mError.Truncate();
mInnerWindowID = 0;
mWindowIDCached = false;
mSheet = nsnull;
mLoader = nsnull;
#endif
if (mPushback != mLocalPushback) {
delete [] mPushback;
mPushback = mLocalPushback;
mPushbackSize = ArrayLength(mLocalPushback);
}
}
// Returns -1 on error or eof
PRInt32
nsCSSScanner::Read()
{
PRInt32 rv;
if (0 < mPushbackCount) {
rv = PRInt32(mPushback[--mPushbackCount]);
} else {
if (mOffset == mCount) {
return -1;
}
rv = PRInt32(mReadPointer[mOffset++]);
// There are four types of newlines in CSS: "\r", "\n", "\r\n", and "\f".
// To simplify dealing with newlines, they are all normalized to "\n" here
if (rv == '\r') {
if (mOffset < mCount && mReadPointer[mOffset] == '\n') {
mOffset++;
}
rv = '\n';
} else if (rv == '\f') {
rv = '\n';
}
if (rv == '\n') {
// 0 is a magical line number meaning that we don't know (i.e., script)
if (mLineNumber != 0)
++mLineNumber;
#ifdef CSS_REPORT_PARSE_ERRORS
mColNumber = 0;
} else {
mColNumber++;
#endif
}
}
return rv;
}
PRInt32
nsCSSScanner::Peek()
{
if (0 == mPushbackCount) {
PRInt32 ch = Read();
if (ch < 0) {
return -1;
}
mPushback[0] = PRUnichar(ch);
mPushbackCount++;
}
return PRInt32(mPushback[mPushbackCount - 1]);
}
void
nsCSSScanner::Pushback(PRUnichar aChar)
{
if (mPushbackCount == mPushbackSize) { // grow buffer
PRUnichar* newPushback = new PRUnichar[mPushbackSize + 4];
if (nsnull == newPushback) {
return;
}
mPushbackSize += 4;
memcpy(newPushback, mPushback, sizeof(PRUnichar) * mPushbackCount);
if (mPushback != mLocalPushback) {
delete [] mPushback;
}
mPushback = newPushback;
}
mPushback[mPushbackCount++] = aChar;
}
bool
nsCSSScanner::LookAhead(PRUnichar aChar)
{
PRInt32 ch = Read();
if (ch < 0) {
return false;
}
if (ch == aChar) {
return true;
}
Pushback(ch);
return false;
}
bool
nsCSSScanner::LookAheadOrEOF(PRUnichar aChar)
{
PRInt32 ch = Read();
if (ch < 0) {
return true;
}
if (ch == aChar) {
return true;
}
Pushback(ch);
return false;
}
void
nsCSSScanner::EatWhiteSpace()
{
for (;;) {
PRInt32 ch = Read();
if (ch < 0) {
break;
}
if ((ch != ' ') && (ch != '\n') && (ch != '\t')) {
Pushback(ch);
break;
}
}
}
bool
nsCSSScanner::Next(nsCSSToken& aToken)
{
for (;;) { // Infinite loop so we can restart after comments.
PRInt32 ch = Read();
if (ch < 0) {
return false;
}
// UNICODE-RANGE
if ((ch == 'u' || ch == 'U') && Peek() == '+')
return ParseURange(ch, aToken);
// IDENT
if (StartsIdent(ch, Peek()))
return ParseIdent(ch, aToken);
// AT_KEYWORD
if (ch == '@') {
PRInt32 nextChar = Read();
if (nextChar >= 0) {
PRInt32 followingChar = Peek();
Pushback(nextChar);
if (StartsIdent(nextChar, followingChar))
return ParseAtKeyword(ch, aToken);
}
}
// NUMBER or DIM
if ((ch == '.') || (ch == '+') || (ch == '-')) {
PRInt32 nextChar = Peek();
if (IsDigit(nextChar)) {
return ParseNumber(ch, aToken);
}
else if (('.' == nextChar) && ('.' != ch)) {
nextChar = Read();
PRInt32 followingChar = Peek();
Pushback(nextChar);
if (IsDigit(followingChar))
return ParseNumber(ch, aToken);
}
}
if (IsDigit(ch)) {
return ParseNumber(ch, aToken);
}
// ID
if (ch == '#') {
return ParseRef(ch, aToken);
}
// STRING
if ((ch == '"') || (ch == '\'')) {
return ParseString(ch, aToken);
}
// WS
if (IsWhitespace(ch)) {
aToken.mType = eCSSToken_WhiteSpace;
aToken.mIdent.Assign(PRUnichar(ch));
EatWhiteSpace();
return true;
}
if (ch == '/' && !IsSVGMode()) {
PRInt32 nextChar = Peek();
if (nextChar == '*') {
Read();
// FIXME: Editor wants comments to be preserved (bug 60290).
if (!SkipCComment()) {
return false;
}
continue; // start again at the beginning
}
}
if (ch == '<') { // consume HTML comment tags
if (LookAhead('!')) {
if (LookAhead('-')) {
if (LookAhead('-')) {
aToken.mType = eCSSToken_HTMLComment;
aToken.mIdent.AssignLiteral("<!--");
return true;
}
Pushback('-');
}
Pushback('!');
}
}
if (ch == '-') { // check for HTML comment end
if (LookAhead('-')) {
if (LookAhead('>')) {
aToken.mType = eCSSToken_HTMLComment;
aToken.mIdent.AssignLiteral("-->");
return true;
}
Pushback('-');
}
}
// INCLUDES ("~=") and DASHMATCH ("|=")
if (( ch == '|' ) || ( ch == '~' ) || ( ch == '^' ) ||
( ch == '$' ) || ( ch == '*' )) {
PRInt32 nextChar = Read();
if ( nextChar == '=' ) {
if (ch == '~') {
aToken.mType = eCSSToken_Includes;
}
else if (ch == '|') {
aToken.mType = eCSSToken_Dashmatch;
}
else if (ch == '^') {
aToken.mType = eCSSToken_Beginsmatch;
}
else if (ch == '$') {
aToken.mType = eCSSToken_Endsmatch;
}
else if (ch == '*') {
aToken.mType = eCSSToken_Containsmatch;
}
return true;
} else if (nextChar >= 0) {
Pushback(nextChar);
}
}
aToken.mType = eCSSToken_Symbol;
aToken.mSymbol = ch;
return true;
}
}
bool
nsCSSScanner::NextURL(nsCSSToken& aToken)
{
EatWhiteSpace();
PRInt32 ch = Read();
if (ch < 0) {
return false;
}
// STRING
if ((ch == '"') || (ch == '\'')) {
#ifdef DEBUG
bool ok =
#endif
ParseString(ch, aToken);
NS_ABORT_IF_FALSE(ok, "ParseString should never fail, "
"since there's always something read");
NS_ABORT_IF_FALSE(aToken.mType == eCSSToken_String ||
aToken.mType == eCSSToken_Bad_String,
"unexpected token type");
if (NS_LIKELY(aToken.mType == eCSSToken_String)) {
EatWhiteSpace();
if (LookAheadOrEOF(')')) {
aToken.mType = eCSSToken_URL;
} else {
aToken.mType = eCSSToken_Bad_URL;
}
} else {
aToken.mType = eCSSToken_Bad_URL;
}
return true;
}
// Process a url lexical token. A CSS1 url token can contain
// characters beyond identifier characters (e.g. '/', ':', etc.)
// Because of this the normal rules for tokenizing the input don't
// apply very well. To simplify the parser and relax some of the
// requirements on the scanner we parse url's here. If we find a
// malformed URL then we emit a token of type "Bad_URL" so that
// the CSS1 parser can ignore the invalid input. The parser must
// treat a Bad_URL token like a Function token, and process
// tokens until a matching parenthesis.
aToken.mType = eCSSToken_Bad_URL;
aToken.mSymbol = PRUnichar(0);
nsString& ident = aToken.mIdent;
ident.SetLength(0);
// start of a non-quoted url (which may be empty)
bool ok = true;
for (;;) {
if (IsURLChar(ch)) {
// A regular url character.
ident.Append(PRUnichar(ch));
} else if (ch == ')') {
// All done
break;
} else if (IsWhitespace(ch)) {
// Whitespace is allowed at the end of the URL
EatWhiteSpace();
// Consume the close paren if we have it; if not we're an invalid URL.
ok = LookAheadOrEOF(')');
break;
} else if (ch == '\\') {
if (!ParseAndAppendEscape(ident, false)) {
ok = false;
Pushback(ch);
break;
}
} else {
// This is an invalid URL spec
ok = false;
Pushback(ch); // push it back so the parser can match tokens and
// then closing parenthesis
break;
}
ch = Read();
if (ch < 0) {
break;
}
}
// If the result of the above scanning is ok then change the token
// type to a useful one.
if (ok) {
aToken.mType = eCSSToken_URL;
}
return true;
}
/**
* Returns whether an escape was succesfully parsed; if it was not,
* the backslash needs to be its own symbol token.
*/
bool
nsCSSScanner::ParseAndAppendEscape(nsString& aOutput, bool aInString)
{
PRInt32 ch = Read();
if (ch < 0) {
return false;
}
if (IsHexDigit(ch)) {
PRInt32 rv = 0;
int i;
Pushback(ch);
for (i = 0; i < 6; i++) { // up to six digits
ch = Read();
if (ch < 0) {
// Whoops: error or premature eof
break;
}
if (!IsHexDigit(ch) && !IsWhitespace(ch)) {
Pushback(ch);
break;
} else if (IsHexDigit(ch)) {
rv = rv * 16 + HexDigitValue(ch);
} else {
NS_ASSERTION(IsWhitespace(ch), "bad control flow");
// single space ends escape
break;
}
}
if (6 == i) { // look for trailing whitespace and eat it
ch = Peek();
if (IsWhitespace(ch)) {
(void) Read();
}
}
NS_ASSERTION(rv >= 0, "How did rv become negative?");
// "[at most six hexadecimal digits following a backslash] stand
// for the ISO 10646 character with that number, which must not be
// zero. (It is undefined in CSS 2.1 what happens if a style sheet
// does contain a character with Unicode codepoint zero.)"
// -- CSS2.1 section 4.1.3
//
// Silently deleting \0 opens a content-filtration loophole (see
// bug 228856), so what we do instead is pretend the "cancels the
// meaning of special characters" rule applied.
if (rv > 0) {
AppendUCS4ToUTF16(ENSURE_VALID_CHAR(rv), aOutput);
} else {
while (i--)
aOutput.Append('0');
if (IsWhitespace(ch))
Pushback(ch);
}
return true;
}
// "Any character except a hexidecimal digit can be escaped to
// remove its special meaning by putting a backslash in front"
// -- CSS1 spec section 7.1
if (ch == '\n') {
if (!aInString) {
// Outside of strings (which includes url() that contains a
// string), escaped newlines aren't special, and just tokenize as
// eCSSToken_Symbol (DELIM).
Pushback(ch);
return false;
}
// In strings (and in url() containing a string), escaped newlines
// are just dropped to allow splitting over multiple lines.
} else {
aOutput.Append(ch);
}
return true;
}
/**
* Gather up the characters in an identifier. The identfier was
* started by "aChar" which will be appended to aIdent. The result
* will be aIdent with all of the identifier characters appended
* until the first non-identifier character is seen. The termination
* character is unread for the future re-reading.
*
* Returns failure when the character sequence does not form an ident at
* all, in which case the caller is responsible for pushing back or
* otherwise handling aChar. (This occurs only when aChar is '\'.)
*/
bool
nsCSSScanner::GatherIdent(PRInt32 aChar, nsString& aIdent)