1 /*
2  * Copyright (C) 2003 Lars Knoll (knoll@kde.org)
3  * Copyright (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
4  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
5  * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
6  * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
7  * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public License
20  * along with this library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24 
25 #include "config.h"
26 #include "CSSParser.h"
27 
28 #include "CSSBorderImageValue.h"
29 #include "CSSCanvasValue.h"
30 #include "CSSCharsetRule.h"
31 #include "CSSCursorImageValue.h"
32 #include "CSSFontFaceRule.h"
33 #include "CSSFontFaceSrcValue.h"
34 #include "CSSGradientValue.h"
35 #include "CSSImageValue.h"
36 #include "CSSImportRule.h"
37 #include "CSSInheritedValue.h"
38 #include "CSSInitialValue.h"
39 #include "CSSLineBoxContainValue.h"
40 #include "CSSMediaRule.h"
41 #include "CSSMutableStyleDeclaration.h"
42 #include "CSSPageRule.h"
43 #include "CSSPrimitiveValue.h"
44 #include "CSSPrimitiveValueCache.h"
45 #include "CSSProperty.h"
46 #include "CSSPropertyNames.h"
47 #include "CSSPropertySourceData.h"
48 #include "CSSQuirkPrimitiveValue.h"
49 #include "CSSReflectValue.h"
50 #include "CSSRuleList.h"
51 #include "CSSSelector.h"
52 #include "CSSStyleRule.h"
53 #include "CSSStyleSheet.h"
54 #include "CSSTimingFunctionValue.h"
55 #include "CSSUnicodeRangeValue.h"
56 #include "CSSValueKeywords.h"
57 #include "CSSValueList.h"
58 #include "Counter.h"
59 #include "Document.h"
60 #include "FloatConversion.h"
61 #include "FontFamilyValue.h"
62 #include "FontValue.h"
63 #include "HTMLParserIdioms.h"
64 #include "HashTools.h"
65 #include "MediaList.h"
66 #include "MediaQueryExp.h"
67 #include "Page.h"
68 #include "Pair.h"
69 #include "Rect.h"
70 #include "RenderTheme.h"
71 #include "ShadowValue.h"
72 #include "WebKitCSSKeyframeRule.h"
73 #include "WebKitCSSKeyframesRule.h"
74 #include "WebKitCSSTransformValue.h"
75 #include <limits.h>
76 #include <wtf/HexNumber.h>
77 #include <wtf/dtoa.h>
78 #include <wtf/text/StringBuffer.h>
79 
80 #if ENABLE(DASHBOARD_SUPPORT)
81 #include "DashboardRegion.h"
82 #endif
83 
84 #define YYDEBUG 0
85 
86 #if YYDEBUG > 0
87 extern int cssyydebug;
88 #endif
89 
90 extern int cssyyparse(void* parser);
91 
92 using namespace std;
93 using namespace WTF;
94 
95 namespace WebCore {
96 
97 static const unsigned INVALID_NUM_PARSED_PROPERTIES = UINT_MAX;
98 static const double MAX_SCALE = 1000000;
99 
equal(const CSSParserString & a,const char * b)100 static bool equal(const CSSParserString& a, const char* b)
101 {
102     for (int i = 0; i < a.length; ++i) {
103         if (!b[i])
104             return false;
105         if (a.characters[i] != b[i])
106             return false;
107     }
108     return !b[a.length];
109 }
110 
equalIgnoringCase(const CSSParserString & a,const char * b)111 static bool equalIgnoringCase(const CSSParserString& a, const char* b)
112 {
113     for (int i = 0; i < a.length; ++i) {
114         if (!b[i])
115             return false;
116         ASSERT(!isASCIIUpper(b[i]));
117         if (toASCIILower(a.characters[i]) != b[i])
118             return false;
119     }
120     return !b[a.length];
121 }
122 
hasPrefix(const char * string,unsigned length,const char * prefix)123 static bool hasPrefix(const char* string, unsigned length, const char* prefix)
124 {
125     for (unsigned i = 0; i < length; ++i) {
126         if (!prefix[i])
127             return true;
128         if (string[i] != prefix[i])
129             return false;
130     }
131     return false;
132 }
133 
CSSParser(bool strictParsing)134 CSSParser::CSSParser(bool strictParsing)
135     : m_strict(strictParsing)
136     , m_important(false)
137     , m_id(0)
138     , m_styleSheet(0)
139     , m_valueList(0)
140     , m_parsedProperties(static_cast<CSSProperty**>(fastMalloc(32 * sizeof(CSSProperty*))))
141     , m_numParsedProperties(0)
142     , m_maxParsedProperties(32)
143     , m_numParsedPropertiesBeforeMarginBox(INVALID_NUM_PARSED_PROPERTIES)
144     , m_inParseShorthand(0)
145     , m_currentShorthand(0)
146     , m_implicitShorthand(false)
147     , m_hasFontFaceOnlyValues(false)
148     , m_hadSyntacticallyValidCSSRule(false)
149     , m_defaultNamespace(starAtom)
150     , m_inStyleRuleOrDeclaration(false)
151     , m_selectorListRange(0, 0)
152     , m_ruleBodyRange(0, 0)
153     , m_propertyRange(UINT_MAX, UINT_MAX)
154     , m_ruleRangeMap(0)
155     , m_currentRuleData(0)
156     , m_data(0)
157     , yy_start(1)
158     , m_lineNumber(0)
159     , m_lastSelectorLineNumber(0)
160     , m_allowImportRules(true)
161     , m_allowNamespaceDeclarations(true)
162 {
163 #if YYDEBUG > 0
164     cssyydebug = 1;
165 #endif
166     CSSPropertySourceData::init();
167 }
168 
~CSSParser()169 CSSParser::~CSSParser()
170 {
171     clearProperties();
172     fastFree(m_parsedProperties);
173 
174     delete m_valueList;
175 
176     fastFree(m_data);
177 
178     fastDeleteAllValues(m_floatingSelectors);
179     deleteAllValues(m_floatingSelectorVectors);
180     deleteAllValues(m_floatingValueLists);
181     deleteAllValues(m_floatingFunctions);
182 }
183 
lower()184 void CSSParserString::lower()
185 {
186     // FIXME: If we need Unicode lowercasing here, then we probably want the real kind
187     // that can potentially change the length of the string rather than the character
188     // by character kind. If we don't need Unicode lowercasing, it would be good to
189     // simplify this function.
190 
191     if (charactersAreAllASCII(characters, length)) {
192         // Fast case for all-ASCII.
193         for (int i = 0; i < length; i++)
194             characters[i] = toASCIILower(characters[i]);
195     } else {
196         for (int i = 0; i < length; i++)
197             characters[i] = Unicode::toLower(characters[i]);
198     }
199 }
200 
setupParser(const char * prefix,const String & string,const char * suffix)201 void CSSParser::setupParser(const char* prefix, const String& string, const char* suffix)
202 {
203     int length = string.length() + strlen(prefix) + strlen(suffix) + 2;
204 
205     fastFree(m_data);
206     m_data = static_cast<UChar*>(fastMalloc(length * sizeof(UChar)));
207     for (unsigned i = 0; i < strlen(prefix); i++)
208         m_data[i] = prefix[i];
209 
210     memcpy(m_data + strlen(prefix), string.characters(), string.length() * sizeof(UChar));
211 
212     unsigned start = strlen(prefix) + string.length();
213     unsigned end = start + strlen(suffix);
214     for (unsigned i = start; i < end; i++)
215         m_data[i] = suffix[i - start];
216 
217     m_data[length - 1] = 0;
218     m_data[length - 2] = 0;
219 
220     yy_hold_char = 0;
221     yyleng = 0;
222     yytext = yy_c_buf_p = m_data;
223     yy_hold_char = *yy_c_buf_p;
224     resetRuleBodyMarks();
225 }
226 
parseSheet(CSSStyleSheet * sheet,const String & string,int startLineNumber,StyleRuleRangeMap * ruleRangeMap)227 void CSSParser::parseSheet(CSSStyleSheet* sheet, const String& string, int startLineNumber, StyleRuleRangeMap* ruleRangeMap)
228 {
229     setStyleSheet(sheet);
230     m_defaultNamespace = starAtom; // Reset the default namespace.
231     m_ruleRangeMap = ruleRangeMap;
232     if (ruleRangeMap) {
233         m_currentRuleData = CSSRuleSourceData::create();
234         m_currentRuleData->styleSourceData = CSSStyleSourceData::create();
235     }
236 
237     m_lineNumber = startLineNumber;
238     setupParser("", string, "");
239     cssyyparse(this);
240     m_ruleRangeMap = 0;
241     m_currentRuleData = 0;
242     m_rule = 0;
243 }
244 
parseRule(CSSStyleSheet * sheet,const String & string)245 PassRefPtr<CSSRule> CSSParser::parseRule(CSSStyleSheet* sheet, const String& string)
246 {
247     setStyleSheet(sheet);
248     m_allowNamespaceDeclarations = false;
249     setupParser("@-webkit-rule{", string, "} ");
250     cssyyparse(this);
251     return m_rule.release();
252 }
253 
parseKeyframeRule(CSSStyleSheet * sheet,const String & string)254 PassRefPtr<CSSRule> CSSParser::parseKeyframeRule(CSSStyleSheet *sheet, const String &string)
255 {
256     setStyleSheet(sheet);
257     setupParser("@-webkit-keyframe-rule{ ", string, "} ");
258     cssyyparse(this);
259     return m_keyframe.release();
260 }
261 
isColorPropertyID(int propertyId)262 static inline bool isColorPropertyID(int propertyId)
263 {
264     switch (propertyId) {
265     case CSSPropertyColor:
266     case CSSPropertyBackgroundColor:
267     case CSSPropertyBorderBottomColor:
268     case CSSPropertyBorderLeftColor:
269     case CSSPropertyBorderRightColor:
270     case CSSPropertyBorderTopColor:
271     case CSSPropertyOutlineColor:
272     case CSSPropertyTextLineThroughColor:
273     case CSSPropertyTextOverlineColor:
274     case CSSPropertyTextUnderlineColor:
275     case CSSPropertyWebkitBorderAfterColor:
276     case CSSPropertyWebkitBorderBeforeColor:
277     case CSSPropertyWebkitBorderEndColor:
278     case CSSPropertyWebkitBorderStartColor:
279     case CSSPropertyWebkitColumnRuleColor:
280     case CSSPropertyWebkitTextEmphasisColor:
281     case CSSPropertyWebkitTextFillColor:
282     case CSSPropertyWebkitTextStrokeColor:
283         return true;
284     default:
285         return false;
286     }
287 }
288 
parseColorValue(CSSMutableStyleDeclaration * declaration,int propertyId,const String & string,bool important,bool strict)289 static bool parseColorValue(CSSMutableStyleDeclaration* declaration, int propertyId, const String& string, bool important, bool strict)
290 {
291     if (!string.length())
292         return false;
293     if (!isColorPropertyID(propertyId))
294         return false;
295     CSSParserString cssString;
296     cssString.characters = const_cast<UChar*>(string.characters());
297     cssString.length = string.length();
298     int valueID = cssValueKeywordID(cssString);
299     bool validPrimitive = false;
300     if (valueID == CSSValueWebkitText)
301         validPrimitive = true;
302     else if (valueID == CSSValueCurrentcolor)
303         validPrimitive = true;
304     else if ((valueID >= CSSValueAqua && valueID <= CSSValueWindowtext) || valueID == CSSValueMenu
305              || (valueID >= CSSValueWebkitFocusRingColor && valueID < CSSValueWebkitText && !strict)) {
306         validPrimitive = true;
307     }
308 
309     CSSStyleSheet* stylesheet = static_cast<CSSStyleSheet*>(declaration->stylesheet());
310     if (!stylesheet || !stylesheet->document())
311         return false;
312     if (validPrimitive) {
313         CSSProperty property(propertyId, stylesheet->document()->cssPrimitiveValueCache()->createIdentifierValue(valueID), important);
314         declaration->addParsedProperty(property);
315         return true;
316     }
317     RGBA32 color;
318     if (!CSSParser::parseColor(string, color, strict && string[0] != '#'))
319         return false;
320     CSSProperty property(propertyId, stylesheet->document()->cssPrimitiveValueCache()->createColorValue(color), important);
321     declaration->addParsedProperty(property);
322     return true;
323 }
324 
isSimpleLengthPropertyID(int propertyId,bool & acceptsNegativeNumbers)325 static inline bool isSimpleLengthPropertyID(int propertyId, bool& acceptsNegativeNumbers)
326 {
327     switch (propertyId) {
328     case CSSPropertyFontSize:
329     case CSSPropertyHeight:
330     case CSSPropertyWidth:
331     case CSSPropertyMinHeight:
332     case CSSPropertyMinWidth:
333     case CSSPropertyPaddingBottom:
334     case CSSPropertyPaddingLeft:
335     case CSSPropertyPaddingRight:
336     case CSSPropertyPaddingTop:
337     case CSSPropertyWebkitLogicalWidth:
338     case CSSPropertyWebkitLogicalHeight:
339     case CSSPropertyWebkitMinLogicalWidth:
340     case CSSPropertyWebkitMinLogicalHeight:
341     case CSSPropertyWebkitPaddingAfter:
342     case CSSPropertyWebkitPaddingBefore:
343     case CSSPropertyWebkitPaddingEnd:
344     case CSSPropertyWebkitPaddingStart:
345         acceptsNegativeNumbers = false;
346         return true;
347     case CSSPropertyBottom:
348     case CSSPropertyLeft:
349     case CSSPropertyMarginBottom:
350     case CSSPropertyMarginLeft:
351     case CSSPropertyMarginRight:
352     case CSSPropertyMarginTop:
353     case CSSPropertyRight:
354     case CSSPropertyTextIndent:
355     case CSSPropertyTop:
356     case CSSPropertyWebkitMarginAfter:
357     case CSSPropertyWebkitMarginBefore:
358     case CSSPropertyWebkitMarginEnd:
359     case CSSPropertyWebkitMarginStart:
360         acceptsNegativeNumbers = true;
361         return true;
362     default:
363         return false;
364     }
365 }
366 
parseSimpleLengthValue(CSSMutableStyleDeclaration * declaration,int propertyId,const String & string,bool important,bool strict)367 static bool parseSimpleLengthValue(CSSMutableStyleDeclaration* declaration, int propertyId, const String& string, bool important, bool strict)
368 {
369     const UChar* characters = string.characters();
370     unsigned length = string.length();
371     if (!characters || !length)
372         return false;
373     bool acceptsNegativeNumbers;
374     if (!isSimpleLengthPropertyID(propertyId, acceptsNegativeNumbers))
375         return false;
376 
377     CSSPrimitiveValue::UnitTypes unit = CSSPrimitiveValue::CSS_NUMBER;
378     if (length > 2 && characters[length - 2] == 'p' && characters[length - 1] == 'x') {
379         length -= 2;
380         unit = CSSPrimitiveValue::CSS_PX;
381     } else if (length > 1 && characters[length - 1] == '%') {
382         length -= 1;
383         unit = CSSPrimitiveValue::CSS_PERCENTAGE;
384     }
385 
386     // We rely on charactersToDouble for validation as well. The function
387     // will set "ok" to "false" if the entire passed-in character range does
388     // not represent a double.
389     bool ok;
390     double number = charactersToDouble(characters, length, &ok);
391     if (!ok)
392         return false;
393     if (unit == CSSPrimitiveValue::CSS_NUMBER) {
394         if (number && strict)
395             return false;
396         unit = CSSPrimitiveValue::CSS_PX;
397     }
398     if (number < 0 && !acceptsNegativeNumbers)
399         return false;
400 
401     CSSStyleSheet* stylesheet = static_cast<CSSStyleSheet*>(declaration->stylesheet());
402     if (!stylesheet || !stylesheet->document())
403         return false;
404     CSSProperty property(propertyId, stylesheet->document()->cssPrimitiveValueCache()->createValue(number, unit), important);
405     declaration->addParsedProperty(property);
406     return true;
407 }
408 
parseValue(CSSMutableStyleDeclaration * declaration,int propertyId,const String & string,bool important,bool strict)409 bool CSSParser::parseValue(CSSMutableStyleDeclaration* declaration, int propertyId, const String& string, bool important, bool strict)
410 {
411     if (parseSimpleLengthValue(declaration, propertyId, string, important, strict))
412         return true;
413     if (parseColorValue(declaration, propertyId, string, important, strict))
414         return true;
415     CSSParser parser(strict);
416     return parser.parseValue(declaration, propertyId, string, important);
417 }
418 
parseValue(CSSMutableStyleDeclaration * declaration,int propertyId,const String & string,bool important)419 bool CSSParser::parseValue(CSSMutableStyleDeclaration* declaration, int propertyId, const String& string, bool important)
420 {
421     ASSERT(!declaration->stylesheet() || declaration->stylesheet()->isCSSStyleSheet());
422     setStyleSheet(static_cast<CSSStyleSheet*>(declaration->stylesheet()));
423 
424     setupParser("@-webkit-value{", string, "} ");
425 
426     m_id = propertyId;
427     m_important = important;
428 
429     cssyyparse(this);
430 
431     m_rule = 0;
432 
433     bool ok = false;
434     if (m_hasFontFaceOnlyValues)
435         deleteFontFaceOnlyValues();
436     if (m_numParsedProperties) {
437         ok = true;
438         declaration->addParsedProperties(m_parsedProperties, m_numParsedProperties);
439         clearProperties();
440     }
441 
442     return ok;
443 }
444 
445 // color will only be changed when string contains a valid css color, making it
446 // possible to set up a default color.
parseColor(RGBA32 & color,const String & string,bool strict)447 bool CSSParser::parseColor(RGBA32& color, const String& string, bool strict)
448 {
449     // First try creating a color specified by name, rgba(), rgb() or "#" syntax.
450     if (parseColor(string, color, strict))
451         return true;
452 
453     CSSParser parser(true);
454     RefPtr<CSSMutableStyleDeclaration> dummyStyleDeclaration = CSSMutableStyleDeclaration::create();
455 
456     // Now try to create a color from rgba() syntax.
457     if (!parser.parseColor(dummyStyleDeclaration.get(), string))
458         return false;
459 
460     CSSValue* value = parser.m_parsedProperties[0]->value();
461     if (value->cssValueType() != CSSValue::CSS_PRIMITIVE_VALUE)
462         return false;
463 
464     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
465     if (primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_RGBCOLOR)
466         return false;
467 
468     color = primitiveValue->getRGBA32Value();
469     return true;
470 }
471 
parseColor(CSSMutableStyleDeclaration * declaration,const String & string)472 bool CSSParser::parseColor(CSSMutableStyleDeclaration* declaration, const String& string)
473 {
474     ASSERT(!declaration->stylesheet() || declaration->stylesheet()->isCSSStyleSheet());
475     setStyleSheet(static_cast<CSSStyleSheet*>(declaration->stylesheet()));
476 
477     setupParser("@-webkit-decls{color:", string, "} ");
478     cssyyparse(this);
479     m_rule = 0;
480 
481     return (m_numParsedProperties && m_parsedProperties[0]->m_id == CSSPropertyColor);
482 }
483 
parseSystemColor(RGBA32 & color,const String & string,Document * document)484 bool CSSParser::parseSystemColor(RGBA32& color, const String& string, Document* document)
485 {
486     if (!document || !document->page())
487         return false;
488 
489     CSSParserString cssColor;
490     cssColor.characters = const_cast<UChar*>(string.characters());
491     cssColor.length = string.length();
492     int id = cssValueKeywordID(cssColor);
493     if (id <= 0)
494         return false;
495 
496     color = document->page()->theme()->systemColor(id).rgb();
497     return true;
498 }
499 
parseSelector(const String & string,Document * doc,CSSSelectorList & selectorList)500 void CSSParser::parseSelector(const String& string, Document* doc, CSSSelectorList& selectorList)
501 {
502     RefPtr<CSSStyleSheet> dummyStyleSheet = CSSStyleSheet::create(doc);
503 
504     setStyleSheet(dummyStyleSheet.get());
505     m_selectorListForParseSelector = &selectorList;
506 
507     setupParser("@-webkit-selector{", string, "}");
508 
509     cssyyparse(this);
510 
511     m_selectorListForParseSelector = 0;
512 
513     // The style sheet will be deleted right away, so it won't outlive the document.
514     ASSERT(dummyStyleSheet->hasOneRef());
515 }
516 
parseDeclaration(CSSMutableStyleDeclaration * declaration,const String & string,RefPtr<CSSStyleSourceData> * styleSourceData)517 bool CSSParser::parseDeclaration(CSSMutableStyleDeclaration* declaration, const String& string, RefPtr<CSSStyleSourceData>* styleSourceData)
518 {
519     // Length of the "@-webkit-decls{" prefix.
520     static const unsigned prefixLength = 15;
521 
522     ASSERT(!declaration->stylesheet() || declaration->stylesheet()->isCSSStyleSheet());
523     setStyleSheet(static_cast<CSSStyleSheet*>(declaration->stylesheet()));
524     if (styleSourceData) {
525         m_currentRuleData = CSSRuleSourceData::create();
526         m_currentRuleData->styleSourceData = CSSStyleSourceData::create();
527         m_inStyleRuleOrDeclaration = true;
528     }
529 
530     setupParser("@-webkit-decls{", string, "} ");
531     cssyyparse(this);
532     m_rule = 0;
533 
534     bool ok = false;
535     if (m_hasFontFaceOnlyValues)
536         deleteFontFaceOnlyValues();
537     if (m_numParsedProperties) {
538         ok = true;
539         declaration->addParsedProperties(m_parsedProperties, m_numParsedProperties);
540         clearProperties();
541     }
542 
543     if (m_currentRuleData) {
544         m_currentRuleData->styleSourceData->styleBodyRange.start = 0;
545         m_currentRuleData->styleSourceData->styleBodyRange.end = string.length();
546         for (Vector<CSSPropertySourceData>::iterator it = m_currentRuleData->styleSourceData->propertyData.begin(), endIt = m_currentRuleData->styleSourceData->propertyData.end(); it != endIt; ++it) {
547             (*it).range.start -= prefixLength;
548             (*it).range.end -= prefixLength;
549         }
550     }
551 
552     if (styleSourceData) {
553         *styleSourceData = m_currentRuleData->styleSourceData.release();
554         m_currentRuleData = 0;
555         m_inStyleRuleOrDeclaration = false;
556     }
557     return ok;
558 }
559 
parseMediaQuery(MediaList * queries,const String & string)560 bool CSSParser::parseMediaQuery(MediaList* queries, const String& string)
561 {
562     if (string.isEmpty())
563         return true;
564 
565     ASSERT(!m_mediaQuery);
566 
567     // can't use { because tokenizer state switches from mediaquery to initial state when it sees { token.
568     // instead insert one " " (which is WHITESPACE in CSSGrammar.y)
569     setupParser("@-webkit-mediaquery ", string, "} ");
570     cssyyparse(this);
571 
572     bool ok = false;
573     if (m_mediaQuery) {
574         ok = true;
575         queries->appendMediaQuery(m_mediaQuery.release());
576     }
577 
578     return ok;
579 }
580 
581 
addProperty(int propId,PassRefPtr<CSSValue> value,bool important)582 void CSSParser::addProperty(int propId, PassRefPtr<CSSValue> value, bool important)
583 {
584     OwnPtr<CSSProperty> prop(adoptPtr(new CSSProperty(propId, value, important, m_currentShorthand, m_implicitShorthand)));
585     if (m_numParsedProperties >= m_maxParsedProperties) {
586         m_maxParsedProperties += 32;
587         if (m_maxParsedProperties > UINT_MAX / sizeof(CSSProperty*))
588             return;
589         m_parsedProperties = static_cast<CSSProperty**>(fastRealloc(m_parsedProperties,
590             m_maxParsedProperties * sizeof(CSSProperty*)));
591     }
592     m_parsedProperties[m_numParsedProperties++] = prop.leakPtr();
593 }
594 
rollbackLastProperties(int num)595 void CSSParser::rollbackLastProperties(int num)
596 {
597     ASSERT(num >= 0);
598     ASSERT(m_numParsedProperties >= static_cast<unsigned>(num));
599 
600     for (int i = 0; i < num; ++i)
601         delete m_parsedProperties[--m_numParsedProperties];
602 }
603 
clearProperties()604 void CSSParser::clearProperties()
605 {
606     for (unsigned i = 0; i < m_numParsedProperties; i++)
607         delete m_parsedProperties[i];
608     m_numParsedProperties = 0;
609     m_numParsedPropertiesBeforeMarginBox = INVALID_NUM_PARSED_PROPERTIES;
610     m_hasFontFaceOnlyValues = false;
611 }
612 
setStyleSheet(CSSStyleSheet * styleSheet)613 void CSSParser::setStyleSheet(CSSStyleSheet* styleSheet)
614 {
615     m_styleSheet = styleSheet;
616     m_primitiveValueCache = document() ? document()->cssPrimitiveValueCache() : CSSPrimitiveValueCache::create();
617 }
618 
document() const619 Document* CSSParser::document() const
620 {
621     StyleBase* root = m_styleSheet;
622     while (root && root->parent())
623         root = root->parent();
624     if (!root)
625         return 0;
626     if (!root->isCSSStyleSheet())
627         return 0;
628     return static_cast<CSSStyleSheet*>(root)->document();
629 }
630 
validUnit(CSSParserValue * value,Units unitflags,bool strict)631 bool CSSParser::validUnit(CSSParserValue* value, Units unitflags, bool strict)
632 {
633     bool b = false;
634     switch (value->unit) {
635     case CSSPrimitiveValue::CSS_NUMBER:
636         b = (unitflags & FNumber);
637         if (!b && ((unitflags & (FLength | FAngle | FTime)) && (value->fValue == 0 || !strict))) {
638             value->unit = (unitflags & FLength) ? CSSPrimitiveValue::CSS_PX :
639                           ((unitflags & FAngle) ? CSSPrimitiveValue::CSS_DEG : CSSPrimitiveValue::CSS_MS);
640             b = true;
641         }
642         if (!b && (unitflags & FInteger) && value->isInt)
643             b = true;
644         break;
645     case CSSPrimitiveValue::CSS_PERCENTAGE:
646         b = (unitflags & FPercent);
647         break;
648     case CSSParserValue::Q_EMS:
649     case CSSPrimitiveValue::CSS_EMS:
650     case CSSPrimitiveValue::CSS_REMS:
651     case CSSPrimitiveValue::CSS_EXS:
652     case CSSPrimitiveValue::CSS_PX:
653     case CSSPrimitiveValue::CSS_CM:
654     case CSSPrimitiveValue::CSS_MM:
655     case CSSPrimitiveValue::CSS_IN:
656     case CSSPrimitiveValue::CSS_PT:
657     case CSSPrimitiveValue::CSS_PC:
658         b = (unitflags & FLength);
659         break;
660     case CSSPrimitiveValue::CSS_MS:
661     case CSSPrimitiveValue::CSS_S:
662         b = (unitflags & FTime);
663         break;
664     case CSSPrimitiveValue::CSS_DEG:
665     case CSSPrimitiveValue::CSS_RAD:
666     case CSSPrimitiveValue::CSS_GRAD:
667     case CSSPrimitiveValue::CSS_TURN:
668         b = (unitflags & FAngle);
669         break;
670     case CSSPrimitiveValue::CSS_HZ:
671     case CSSPrimitiveValue::CSS_KHZ:
672     case CSSPrimitiveValue::CSS_DIMENSION:
673     default:
674         break;
675     }
676     if (b && unitflags & FNonNeg && value->fValue < 0)
677         b = false;
678     return b;
679 }
680 
unitFromString(CSSParserValue * value)681 static int unitFromString(CSSParserValue* value)
682 {
683     if (value->unit != CSSPrimitiveValue::CSS_IDENT || value->id)
684         return 0;
685 
686     if (equal(value->string, "em"))
687         return CSSPrimitiveValue::CSS_EMS;
688     if (equal(value->string, "rem"))
689         return CSSPrimitiveValue::CSS_REMS;
690     if (equal(value->string, "ex"))
691         return CSSPrimitiveValue::CSS_EXS;
692     if (equal(value->string, "px"))
693         return CSSPrimitiveValue::CSS_PX;
694     if (equal(value->string, "cm"))
695         return CSSPrimitiveValue::CSS_CM;
696     if (equal(value->string, "mm"))
697         return CSSPrimitiveValue::CSS_MM;
698     if (equal(value->string, "in"))
699         return CSSPrimitiveValue::CSS_IN;
700     if (equal(value->string, "pt"))
701         return CSSPrimitiveValue::CSS_PT;
702     if (equal(value->string, "pc"))
703         return CSSPrimitiveValue::CSS_PC;
704     if (equal(value->string, "deg"))
705         return CSSPrimitiveValue::CSS_DEG;
706     if (equal(value->string, "rad"))
707         return CSSPrimitiveValue::CSS_RAD;
708     if (equal(value->string, "grad"))
709         return CSSPrimitiveValue::CSS_GRAD;
710     if (equal(value->string, "turn"))
711         return CSSPrimitiveValue::CSS_TURN;
712     if (equal(value->string, "ms"))
713         return CSSPrimitiveValue::CSS_MS;
714     if (equal(value->string, "s"))
715         return CSSPrimitiveValue::CSS_S;
716     if (equal(value->string, "Hz"))
717         return CSSPrimitiveValue::CSS_HZ;
718     if (equal(value->string, "kHz"))
719         return CSSPrimitiveValue::CSS_KHZ;
720 
721     return 0;
722 }
723 
checkForOrphanedUnits()724 void CSSParser::checkForOrphanedUnits()
725 {
726     if (m_strict || inShorthand())
727         return;
728 
729     // The purpose of this code is to implement the WinIE quirk that allows unit types to be separated from their numeric values
730     // by whitespace, so e.g., width: 20 px instead of width:20px.  This is invalid CSS, so we don't do this in strict mode.
731     CSSParserValue* numericVal = 0;
732     unsigned size = m_valueList->size();
733     for (unsigned i = 0; i < size; i++) {
734         CSSParserValue* value = m_valueList->valueAt(i);
735 
736         if (numericVal) {
737             // Change the unit type of the numeric val to match.
738             int unit = unitFromString(value);
739             if (unit) {
740                 numericVal->unit = unit;
741                 numericVal = 0;
742 
743                 // Now delete the bogus unit value.
744                 m_valueList->deleteValueAt(i);
745                 i--; // We're safe even though |i| is unsigned, since we only hit this code if we had a previous numeric value (so |i| is always > 0 here).
746                 size--;
747                 continue;
748             }
749         }
750 
751         numericVal = (value->unit == CSSPrimitiveValue::CSS_NUMBER) ? value : 0;
752     }
753 }
754 
parseValue(int propId,bool important)755 bool CSSParser::parseValue(int propId, bool important)
756 {
757     if (!m_valueList)
758         return false;
759 
760     CSSParserValue* value = m_valueList->current();
761 
762     if (!value)
763         return false;
764 
765     int id = value->id;
766 
767     // In quirks mode, we will look for units that have been incorrectly separated from the number they belong to
768     // by a space.  We go ahead and associate the unit with the number even though it is invalid CSS.
769     checkForOrphanedUnits();
770 
771     int num = inShorthand() ? 1 : m_valueList->size();
772 
773     if (id == CSSValueInherit) {
774         if (num != 1)
775             return false;
776         addProperty(propId, CSSInheritedValue::create(), important);
777         return true;
778     }
779     else if (id == CSSValueInitial) {
780         if (num != 1)
781             return false;
782         addProperty(propId, CSSInitialValue::createExplicit(), important);
783         return true;
784     }
785 
786     bool validPrimitive = false;
787     RefPtr<CSSValue> parsedValue;
788 
789     switch (static_cast<CSSPropertyID>(propId)) {
790         /* The comment to the left defines all valid value of this properties as defined
791          * in CSS 2, Appendix F. Property index
792          */
793 
794         /* All the CSS properties are not supported by the renderer at the moment.
795          * Note that all the CSS2 Aural properties are only checked, if CSS_AURAL is defined
796          * (see parseAuralValues). As we don't support them at all this seems reasonable.
797          */
798 
799     case CSSPropertySize:                 // <length>{1,2} | auto | [ <page-size> || [ portrait | landscape] ]
800         return parseSize(propId, important);
801 
802     case CSSPropertyQuotes:               // [<string> <string>]+ | none | inherit
803         if (id)
804             validPrimitive = true;
805         else
806             return parseQuotes(propId, important);
807         break;
808     case CSSPropertyUnicodeBidi: // normal | embed | bidi-override | isolate | inherit
809         if (id == CSSValueNormal
810             || id == CSSValueEmbed
811             || id == CSSValueBidiOverride
812             || id == CSSValueWebkitIsolate)
813             validPrimitive = true;
814         break;
815 
816     case CSSPropertyPosition:             // static | relative | absolute | fixed | inherit
817         if (id == CSSValueStatic ||
818              id == CSSValueRelative ||
819              id == CSSValueAbsolute ||
820              id == CSSValueFixed)
821             validPrimitive = true;
822         break;
823 
824     case CSSPropertyPageBreakAfter:     // auto | always | avoid | left | right | inherit
825     case CSSPropertyPageBreakBefore:
826     case CSSPropertyWebkitColumnBreakAfter:
827     case CSSPropertyWebkitColumnBreakBefore:
828         if (id == CSSValueAuto ||
829              id == CSSValueAlways ||
830              id == CSSValueAvoid ||
831              id == CSSValueLeft ||
832              id == CSSValueRight)
833             validPrimitive = true;
834         break;
835 
836     case CSSPropertyPageBreakInside:    // avoid | auto | inherit
837     case CSSPropertyWebkitColumnBreakInside:
838         if (id == CSSValueAuto || id == CSSValueAvoid)
839             validPrimitive = true;
840         break;
841 
842     case CSSPropertyEmptyCells:          // show | hide | inherit
843         if (id == CSSValueShow ||
844              id == CSSValueHide)
845             validPrimitive = true;
846         break;
847 
848     case CSSPropertyContent:              // [ <string> | <uri> | <counter> | attr(X) | open-quote |
849         // close-quote | no-open-quote | no-close-quote ]+ | inherit
850         return parseContent(propId, important);
851 
852     case CSSPropertyWhiteSpace:          // normal | pre | nowrap | inherit
853         if (id == CSSValueNormal ||
854             id == CSSValuePre ||
855             id == CSSValuePreWrap ||
856             id == CSSValuePreLine ||
857             id == CSSValueNowrap)
858             validPrimitive = true;
859         break;
860 
861     case CSSPropertyClip:                 // <shape> | auto | inherit
862         if (id == CSSValueAuto)
863             validPrimitive = true;
864         else if (value->unit == CSSParserValue::Function)
865             return parseShape(propId, important);
866         break;
867 
868     /* Start of supported CSS properties with validation. This is needed for parseShorthand to work
869      * correctly and allows optimization in WebCore::applyRule(..)
870      */
871     case CSSPropertyCaptionSide:         // top | bottom | left | right | inherit
872         if (id == CSSValueLeft || id == CSSValueRight ||
873             id == CSSValueTop || id == CSSValueBottom)
874             validPrimitive = true;
875         break;
876 
877     case CSSPropertyBorderCollapse:      // collapse | separate | inherit
878         if (id == CSSValueCollapse || id == CSSValueSeparate)
879             validPrimitive = true;
880         break;
881 
882     case CSSPropertyVisibility:           // visible | hidden | collapse | inherit
883         if (id == CSSValueVisible || id == CSSValueHidden || id == CSSValueCollapse)
884             validPrimitive = true;
885         break;
886 
887     case CSSPropertyOverflow: {
888         ShorthandScope scope(this, propId);
889         if (num != 1 || !parseValue(CSSPropertyOverflowX, important))
890             return false;
891         CSSValue* value = m_parsedProperties[m_numParsedProperties - 1]->value();
892         addProperty(CSSPropertyOverflowY, value, important);
893         return true;
894     }
895     case CSSPropertyOverflowX:
896     case CSSPropertyOverflowY:           // visible | hidden | scroll | auto | marquee | overlay | inherit
897         if (id == CSSValueVisible || id == CSSValueHidden || id == CSSValueScroll || id == CSSValueAuto ||
898             id == CSSValueOverlay || id == CSSValueWebkitMarquee)
899             validPrimitive = true;
900         break;
901 
902     case CSSPropertyListStylePosition:  // inside | outside | inherit
903         if (id == CSSValueInside || id == CSSValueOutside)
904             validPrimitive = true;
905         break;
906 
907     case CSSPropertyListStyleType:
908         // See section CSS_PROP_LIST_STYLE_TYPE of file CSSValueKeywords.in
909         // for the list of supported list-style-types.
910         if ((id >= CSSValueDisc && id <= CSSValueKatakanaIroha) || id == CSSValueNone)
911             validPrimitive = true;
912         break;
913 
914     case CSSPropertyDisplay:
915         // inline | block | list-item | run-in | inline-block | table |
916         // inline-table | table-row-group | table-header-group | table-footer-group | table-row |
917         // table-column-group | table-column | table-cell | table-caption | box | inline-box | none | inherit
918 #if ENABLE(WCSS)
919         if ((id >= CSSValueInline && id <= CSSValueWapMarquee) || id == CSSValueNone)
920 #else
921         if ((id >= CSSValueInline && id <= CSSValueWebkitInlineBox) || id == CSSValueNone)
922 #endif
923             validPrimitive = true;
924         break;
925 
926     case CSSPropertyDirection:            // ltr | rtl | inherit
927         if (id == CSSValueLtr || id == CSSValueRtl)
928             validPrimitive = true;
929         break;
930 
931     case CSSPropertyTextTransform:       // capitalize | uppercase | lowercase | none | inherit
932         if ((id >= CSSValueCapitalize && id <= CSSValueLowercase) || id == CSSValueNone)
933             validPrimitive = true;
934         break;
935 
936     case CSSPropertyFloat:                // left | right | none | inherit + center for buggy CSS
937         if (id == CSSValueLeft || id == CSSValueRight ||
938              id == CSSValueNone || id == CSSValueCenter)
939             validPrimitive = true;
940         break;
941 
942     case CSSPropertyClear:                // none | left | right | both | inherit
943         if (id == CSSValueNone || id == CSSValueLeft ||
944              id == CSSValueRight|| id == CSSValueBoth)
945             validPrimitive = true;
946         break;
947 
948     case CSSPropertyTextAlign:
949         // left | right | center | justify | webkit_left | webkit_right | webkit_center | webkit_match_parent |
950         // start | end | <string> | inherit
951         if ((id >= CSSValueWebkitAuto && id <= CSSValueWebkitMatchParent) || id == CSSValueStart || id == CSSValueEnd
952              || value->unit == CSSPrimitiveValue::CSS_STRING)
953             validPrimitive = true;
954         break;
955 
956     case CSSPropertyOutlineStyle:        // (<border-style> except hidden) | auto | inherit
957         if (id == CSSValueAuto || id == CSSValueNone || (id >= CSSValueInset && id <= CSSValueDouble))
958             validPrimitive = true;
959         break;
960 
961     case CSSPropertyBorderTopStyle:     //// <border-style> | inherit
962     case CSSPropertyBorderRightStyle:   //   Defined as:    none | hidden | dotted | dashed |
963     case CSSPropertyBorderBottomStyle:  //   solid | double | groove | ridge | inset | outset
964     case CSSPropertyBorderLeftStyle:
965     case CSSPropertyWebkitBorderStartStyle:
966     case CSSPropertyWebkitBorderEndStyle:
967     case CSSPropertyWebkitBorderBeforeStyle:
968     case CSSPropertyWebkitBorderAfterStyle:
969     case CSSPropertyWebkitColumnRuleStyle:
970         if (id >= CSSValueNone && id <= CSSValueDouble)
971             validPrimitive = true;
972         break;
973 
974     case CSSPropertyFontWeight:  // normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit
975         return parseFontWeight(important);
976 
977     case CSSPropertyBorderSpacing: {
978         const int properties[2] = { CSSPropertyWebkitBorderHorizontalSpacing,
979                                     CSSPropertyWebkitBorderVerticalSpacing };
980         if (num == 1) {
981             ShorthandScope scope(this, CSSPropertyBorderSpacing);
982             if (!parseValue(properties[0], important))
983                 return false;
984             CSSValue* value = m_parsedProperties[m_numParsedProperties-1]->value();
985             addProperty(properties[1], value, important);
986             return true;
987         }
988         else if (num == 2) {
989             ShorthandScope scope(this, CSSPropertyBorderSpacing);
990             if (!parseValue(properties[0], important) || !parseValue(properties[1], important))
991                 return false;
992             return true;
993         }
994         return false;
995     }
996     case CSSPropertyWebkitBorderHorizontalSpacing:
997     case CSSPropertyWebkitBorderVerticalSpacing:
998         validPrimitive = validUnit(value, FLength | FNonNeg, m_strict);
999         break;
1000     case CSSPropertyOutlineColor:        // <color> | invert | inherit
1001         // Outline color has "invert" as additional keyword.
1002         // Also, we want to allow the special focus color even in strict parsing mode.
1003         if (id == CSSValueInvert || id == CSSValueWebkitFocusRingColor) {
1004             validPrimitive = true;
1005             break;
1006         }
1007         /* nobreak */
1008     case CSSPropertyBackgroundColor: // <color> | inherit
1009     case CSSPropertyBorderTopColor: // <color> | inherit
1010     case CSSPropertyBorderRightColor:
1011     case CSSPropertyBorderBottomColor:
1012     case CSSPropertyBorderLeftColor:
1013     case CSSPropertyWebkitBorderStartColor:
1014     case CSSPropertyWebkitBorderEndColor:
1015     case CSSPropertyWebkitBorderBeforeColor:
1016     case CSSPropertyWebkitBorderAfterColor:
1017     case CSSPropertyColor: // <color> | inherit
1018     case CSSPropertyTextLineThroughColor: // CSS3 text decoration colors
1019     case CSSPropertyTextUnderlineColor:
1020     case CSSPropertyTextOverlineColor:
1021     case CSSPropertyWebkitColumnRuleColor:
1022     case CSSPropertyWebkitTextEmphasisColor:
1023     case CSSPropertyWebkitTextFillColor:
1024     case CSSPropertyWebkitTextStrokeColor:
1025         if (id == CSSValueWebkitText)
1026             validPrimitive = true; // Always allow this, even when strict parsing is on,
1027                                     // since we use this in our UA sheets.
1028         else if (id == CSSValueCurrentcolor)
1029             validPrimitive = true;
1030         else if ((id >= CSSValueAqua && id <= CSSValueWindowtext) || id == CSSValueMenu ||
1031              (id >= CSSValueWebkitFocusRingColor && id < CSSValueWebkitText && !m_strict)) {
1032             validPrimitive = true;
1033         } else {
1034             parsedValue = parseColor();
1035             if (parsedValue)
1036                 m_valueList->next();
1037         }
1038         break;
1039 
1040     case CSSPropertyCursor: {
1041         // [<uri>,]*  [ auto | crosshair | default | pointer | progress | move | e-resize | ne-resize |
1042         // nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize | ew-resize |
1043         // ns-resize | nesw-resize | nwse-resize | col-resize | row-resize | text | wait | help |
1044         // vertical-text | cell | context-menu | alias | copy | no-drop | not-allowed | -webkit-zoom-in
1045         // -webkit-zoom-out | all-scroll | -webkit-grab | -webkit-grabbing ] ] | inherit
1046         RefPtr<CSSValueList> list;
1047         while (value && value->unit == CSSPrimitiveValue::CSS_URI) {
1048             if (!list)
1049                 list = CSSValueList::createCommaSeparated();
1050             String uri = value->string;
1051             Vector<int> coords;
1052             value = m_valueList->next();
1053             while (value && value->unit == CSSPrimitiveValue::CSS_NUMBER) {
1054                 coords.append(int(value->fValue));
1055                 value = m_valueList->next();
1056             }
1057             IntPoint hotSpot(-1, -1);
1058             int nrcoords = coords.size();
1059             if (nrcoords > 0 && nrcoords != 2)
1060                 return false;
1061             if (nrcoords == 2)
1062                 hotSpot = IntPoint(coords[0], coords[1]);
1063 
1064             if (!uri.isNull() && m_styleSheet) {
1065                 // FIXME: The completeURL call should be done when using the CSSCursorImageValue,
1066                 // not when creating it.
1067                 list->append(CSSCursorImageValue::create(m_styleSheet->completeURL(uri), hotSpot));
1068             }
1069 
1070             if ((m_strict && !value) || (value && !(value->unit == CSSParserValue::Operator && value->iValue == ',')))
1071                 return false;
1072             value = m_valueList->next(); // comma
1073         }
1074         if (list) {
1075             if (!value) { // no value after url list (MSIE 5 compatibility)
1076                 if (list->length() != 1)
1077                     return false;
1078             } else if (!m_strict && value->id == CSSValueHand) // MSIE 5 compatibility :/
1079                 list->append(primitiveValueCache()->createIdentifierValue(CSSValuePointer));
1080             else if (value && ((value->id >= CSSValueAuto && value->id <= CSSValueWebkitGrabbing) || value->id == CSSValueCopy || value->id == CSSValueNone))
1081                 list->append(primitiveValueCache()->createIdentifierValue(value->id));
1082             m_valueList->next();
1083             parsedValue = list.release();
1084             break;
1085         }
1086         id = value->id;
1087         if (!m_strict && value->id == CSSValueHand) { // MSIE 5 compatibility :/
1088             id = CSSValuePointer;
1089             validPrimitive = true;
1090         } else if ((value->id >= CSSValueAuto && value->id <= CSSValueWebkitGrabbing) || value->id == CSSValueCopy || value->id == CSSValueNone)
1091             validPrimitive = true;
1092         break;
1093     }
1094 
1095     case CSSPropertyBackgroundAttachment:
1096     case CSSPropertyBackgroundClip:
1097     case CSSPropertyWebkitBackgroundClip:
1098     case CSSPropertyWebkitBackgroundComposite:
1099     case CSSPropertyBackgroundImage:
1100     case CSSPropertyBackgroundOrigin:
1101     case CSSPropertyWebkitBackgroundOrigin:
1102     case CSSPropertyBackgroundPosition:
1103     case CSSPropertyBackgroundPositionX:
1104     case CSSPropertyBackgroundPositionY:
1105     case CSSPropertyBackgroundSize:
1106     case CSSPropertyWebkitBackgroundSize:
1107     case CSSPropertyBackgroundRepeat:
1108     case CSSPropertyBackgroundRepeatX:
1109     case CSSPropertyBackgroundRepeatY:
1110     case CSSPropertyWebkitMaskAttachment:
1111     case CSSPropertyWebkitMaskClip:
1112     case CSSPropertyWebkitMaskComposite:
1113     case CSSPropertyWebkitMaskImage:
1114     case CSSPropertyWebkitMaskOrigin:
1115     case CSSPropertyWebkitMaskPosition:
1116     case CSSPropertyWebkitMaskPositionX:
1117     case CSSPropertyWebkitMaskPositionY:
1118     case CSSPropertyWebkitMaskSize:
1119     case CSSPropertyWebkitMaskRepeat:
1120     case CSSPropertyWebkitMaskRepeatX:
1121     case CSSPropertyWebkitMaskRepeatY: {
1122         RefPtr<CSSValue> val1;
1123         RefPtr<CSSValue> val2;
1124         int propId1, propId2;
1125         bool result = false;
1126         if (parseFillProperty(propId, propId1, propId2, val1, val2)) {
1127             OwnPtr<ShorthandScope> shorthandScope;
1128             if (propId == CSSPropertyBackgroundPosition ||
1129                 propId == CSSPropertyBackgroundRepeat ||
1130                 propId == CSSPropertyWebkitMaskPosition ||
1131                 propId == CSSPropertyWebkitMaskRepeat) {
1132                 shorthandScope = adoptPtr(new ShorthandScope(this, propId));
1133             }
1134             addProperty(propId1, val1.release(), important);
1135             if (val2)
1136                 addProperty(propId2, val2.release(), important);
1137             result = true;
1138         }
1139         m_implicitShorthand = false;
1140         return result;
1141     }
1142     case CSSPropertyListStyleImage:     // <uri> | none | inherit
1143         if (id == CSSValueNone) {
1144             parsedValue = CSSImageValue::create();
1145             m_valueList->next();
1146         } else if (value->unit == CSSPrimitiveValue::CSS_URI) {
1147             if (m_styleSheet) {
1148                 // FIXME: The completeURL call should be done when using the CSSImageValue,
1149                 // not when creating it.
1150                 parsedValue = CSSImageValue::create(m_styleSheet->completeURL(value->string));
1151                 m_valueList->next();
1152             }
1153         } else if (isGeneratedImageValue(value)) {
1154             if (parseGeneratedImage(parsedValue))
1155                 m_valueList->next();
1156             else
1157                 return false;
1158         }
1159         break;
1160 
1161     case CSSPropertyWebkitTextStrokeWidth:
1162     case CSSPropertyOutlineWidth:        // <border-width> | inherit
1163     case CSSPropertyBorderTopWidth:     //// <border-width> | inherit
1164     case CSSPropertyBorderRightWidth:   //   Which is defined as
1165     case CSSPropertyBorderBottomWidth:  //   thin | medium | thick | <length>
1166     case CSSPropertyBorderLeftWidth:
1167     case CSSPropertyWebkitBorderStartWidth:
1168     case CSSPropertyWebkitBorderEndWidth:
1169     case CSSPropertyWebkitBorderBeforeWidth:
1170     case CSSPropertyWebkitBorderAfterWidth:
1171     case CSSPropertyWebkitColumnRuleWidth:
1172         if (id == CSSValueThin || id == CSSValueMedium || id == CSSValueThick)
1173             validPrimitive = true;
1174         else
1175             validPrimitive = validUnit(value, FLength | FNonNeg, m_strict);
1176         break;
1177 
1178     case CSSPropertyLetterSpacing:       // normal | <length> | inherit
1179     case CSSPropertyWordSpacing:         // normal | <length> | inherit
1180         if (id == CSSValueNormal)
1181             validPrimitive = true;
1182         else
1183             validPrimitive = validUnit(value, FLength, m_strict);
1184         break;
1185 
1186     case CSSPropertyWordBreak:          // normal | break-all | break-word (this is a custom extension)
1187         if (id == CSSValueNormal || id == CSSValueBreakAll || id == CSSValueBreakWord)
1188             validPrimitive = true;
1189         break;
1190 
1191     case CSSPropertyWordWrap:           // normal | break-word
1192         if (id == CSSValueNormal || id == CSSValueBreakWord)
1193             validPrimitive = true;
1194         break;
1195     case CSSPropertySpeak:           // none | normal | spell-out | digits | literal-punctuation | no-punctuation | inherit
1196         if (id == CSSValueNone || id == CSSValueNormal || id == CSSValueSpellOut || id == CSSValueDigits
1197             || id == CSSValueLiteralPunctuation || id == CSSValueNoPunctuation)
1198             validPrimitive = true;
1199         break;
1200 
1201     case CSSPropertyTextIndent:          // <length> | <percentage> | inherit
1202         validPrimitive = (!id && validUnit(value, FLength | FPercent, m_strict));
1203         break;
1204 
1205     case CSSPropertyPaddingTop:          //// <padding-width> | inherit
1206     case CSSPropertyPaddingRight:        //   Which is defined as
1207     case CSSPropertyPaddingBottom:       //   <length> | <percentage>
1208     case CSSPropertyPaddingLeft:         ////
1209     case CSSPropertyWebkitPaddingStart:
1210     case CSSPropertyWebkitPaddingEnd:
1211     case CSSPropertyWebkitPaddingBefore:
1212     case CSSPropertyWebkitPaddingAfter:
1213         validPrimitive = (!id && validUnit(value, FLength | FPercent | FNonNeg, m_strict));
1214         break;
1215 
1216     case CSSPropertyMaxHeight:           // <length> | <percentage> | none | inherit
1217     case CSSPropertyMaxWidth:            // <length> | <percentage> | none | inherit
1218     case CSSPropertyWebkitMaxLogicalWidth:
1219     case CSSPropertyWebkitMaxLogicalHeight:
1220         if (id == CSSValueNone || id == CSSValueIntrinsic || id == CSSValueMinIntrinsic) {
1221             validPrimitive = true;
1222             break;
1223         }
1224         /* nobreak */
1225     case CSSPropertyMinHeight:           // <length> | <percentage> | inherit
1226     case CSSPropertyMinWidth:            // <length> | <percentage> | inherit
1227     case CSSPropertyWebkitMinLogicalWidth:
1228     case CSSPropertyWebkitMinLogicalHeight:
1229         if (id == CSSValueIntrinsic || id == CSSValueMinIntrinsic)
1230             validPrimitive = true;
1231         else
1232             validPrimitive = (!id && validUnit(value, FLength | FPercent | FNonNeg, m_strict));
1233         break;
1234 
1235     case CSSPropertyFontSize:
1236         // <absolute-size> | <relative-size> | <length> | <percentage> | inherit
1237         if (id >= CSSValueXxSmall && id <= CSSValueLarger)
1238             validPrimitive = true;
1239         else
1240             validPrimitive = (validUnit(value, FLength | FPercent | FNonNeg, m_strict));
1241         break;
1242 
1243     case CSSPropertyFontStyle:           // normal | italic | oblique | inherit
1244         if (id == CSSValueNormal || id == CSSValueItalic || id == CSSValueOblique)
1245             validPrimitive = true;
1246         break;
1247 
1248     case CSSPropertyFontVariant:         // normal | small-caps | inherit
1249         return parseFontVariant(important);
1250 
1251     case CSSPropertyVerticalAlign:
1252         // baseline | sub | super | top | text-top | middle | bottom | text-bottom |
1253         // <percentage> | <length> | inherit
1254 
1255         if (id >= CSSValueBaseline && id <= CSSValueWebkitBaselineMiddle)
1256             validPrimitive = true;
1257         else
1258             validPrimitive = (!id && validUnit(value, FLength | FPercent, m_strict));
1259         break;
1260 
1261     case CSSPropertyHeight:               // <length> | <percentage> | auto | inherit
1262     case CSSPropertyWidth:                // <length> | <percentage> | auto | inherit
1263     case CSSPropertyWebkitLogicalWidth:
1264     case CSSPropertyWebkitLogicalHeight:
1265         if (id == CSSValueAuto || id == CSSValueIntrinsic || id == CSSValueMinIntrinsic)
1266             validPrimitive = true;
1267         else
1268             // ### handle multilength case where we allow relative units
1269             validPrimitive = (!id && validUnit(value, FLength | FPercent | FNonNeg, m_strict));
1270         break;
1271 
1272     case CSSPropertyBottom:               // <length> | <percentage> | auto | inherit
1273     case CSSPropertyLeft:                 // <length> | <percentage> | auto | inherit
1274     case CSSPropertyRight:                // <length> | <percentage> | auto | inherit
1275     case CSSPropertyTop:                  // <length> | <percentage> | auto | inherit
1276     case CSSPropertyMarginTop:           //// <margin-width> | inherit
1277     case CSSPropertyMarginRight:         //   Which is defined as
1278     case CSSPropertyMarginBottom:        //   <length> | <percentage> | auto | inherit
1279     case CSSPropertyMarginLeft:          ////
1280     case CSSPropertyWebkitMarginStart:
1281     case CSSPropertyWebkitMarginEnd:
1282     case CSSPropertyWebkitMarginBefore:
1283     case CSSPropertyWebkitMarginAfter:
1284         if (id == CSSValueAuto)
1285             validPrimitive = true;
1286         else
1287             validPrimitive = (!id && validUnit(value, FLength | FPercent, m_strict));
1288         break;
1289 
1290     case CSSPropertyZIndex:              // auto | <integer> | inherit
1291         if (id == CSSValueAuto) {
1292             validPrimitive = true;
1293             break;
1294         }
1295         /* nobreak */
1296     case CSSPropertyOrphans:              // <integer> | inherit | auto (We've added support for auto for backwards compatibility)
1297     case CSSPropertyWidows:               // <integer> | inherit | auto (Ditto)
1298         if (id == CSSValueAuto)
1299             validPrimitive = true;
1300         else
1301             validPrimitive = (!id && validUnit(value, FInteger, false));
1302         break;
1303 
1304     case CSSPropertyLineHeight:          // normal | <number> | <length> | <percentage> | inherit
1305         if (id == CSSValueNormal)
1306             validPrimitive = true;
1307         else
1308             validPrimitive = (!id && validUnit(value, FNumber | FLength | FPercent | FNonNeg, m_strict));
1309         break;
1310     case CSSPropertyCounterIncrement:    // [ <identifier> <integer>? ]+ | none | inherit
1311         if (id != CSSValueNone)
1312             return parseCounter(propId, 1, important);
1313         validPrimitive = true;
1314         break;
1315      case CSSPropertyCounterReset:        // [ <identifier> <integer>? ]+ | none | inherit
1316         if (id != CSSValueNone)
1317             return parseCounter(propId, 0, important);
1318         validPrimitive = true;
1319         break;
1320     case CSSPropertyFontFamily:
1321         // [[ <family-name> | <generic-family> ],]* [<family-name> | <generic-family>] | inherit
1322     {
1323         parsedValue = parseFontFamily();
1324         break;
1325     }
1326 
1327     case CSSPropertyTextDecoration:
1328     case CSSPropertyWebkitTextDecorationsInEffect:
1329         // none | [ underline || overline || line-through || blink ] | inherit
1330         if (id == CSSValueNone) {
1331             validPrimitive = true;
1332         } else {
1333             RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
1334             bool isValid = true;
1335             while (isValid && value) {
1336                 switch (value->id) {
1337                 case CSSValueBlink:
1338                     break;
1339                 case CSSValueUnderline:
1340                 case CSSValueOverline:
1341                 case CSSValueLineThrough:
1342                     list->append(primitiveValueCache()->createIdentifierValue(value->id));
1343                     break;
1344                 default:
1345                     isValid = false;
1346                 }
1347                 value = m_valueList->next();
1348             }
1349             if (list->length() && isValid) {
1350                 parsedValue = list.release();
1351                 m_valueList->next();
1352             }
1353         }
1354         break;
1355 
1356     case CSSPropertyZoom:          // normal | reset | document | <number> | <percentage> | inherit
1357         if (id == CSSValueNormal || id == CSSValueReset || id == CSSValueDocument)
1358             validPrimitive = true;
1359         else
1360             validPrimitive = (!id && validUnit(value, FNumber | FPercent | FNonNeg, true));
1361         break;
1362 
1363     case CSSPropertyTableLayout:         // auto | fixed | inherit
1364         if (id == CSSValueAuto || id == CSSValueFixed)
1365             validPrimitive = true;
1366         break;
1367 
1368     case CSSPropertySrc:  // Only used within @font-face, so cannot use inherit | initial or be !important.  This is a list of urls or local references.
1369         return parseFontFaceSrc();
1370 
1371     case CSSPropertyUnicodeRange:
1372         return parseFontFaceUnicodeRange();
1373 
1374     /* CSS3 properties */
1375     case CSSPropertyWebkitAppearance:
1376         if ((id >= CSSValueCheckbox && id <= CSSValueTextarea) || id == CSSValueNone)
1377             validPrimitive = true;
1378         break;
1379 
1380     case CSSPropertyWebkitBorderImage:
1381     case CSSPropertyWebkitMaskBoxImage:
1382         if (id == CSSValueNone)
1383             validPrimitive = true;
1384         else {
1385             RefPtr<CSSValue> result;
1386             if (parseBorderImage(propId, important, result)) {
1387                 addProperty(propId, result, important);
1388                 return true;
1389             }
1390         }
1391         break;
1392     case CSSPropertyBorderTopRightRadius:
1393     case CSSPropertyBorderTopLeftRadius:
1394     case CSSPropertyBorderBottomLeftRadius:
1395     case CSSPropertyBorderBottomRightRadius: {
1396         if (num != 1 && num != 2)
1397             return false;
1398         validPrimitive = validUnit(value, FLength | FPercent, m_strict);
1399         if (!validPrimitive)
1400             return false;
1401         RefPtr<CSSPrimitiveValue> parsedValue1 = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit);
1402         RefPtr<CSSPrimitiveValue> parsedValue2;
1403         if (num == 2) {
1404             value = m_valueList->next();
1405             validPrimitive = validUnit(value, FLength | FPercent, m_strict);
1406             if (!validPrimitive)
1407                 return false;
1408             parsedValue2 = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit);
1409         } else
1410             parsedValue2 = parsedValue1;
1411 
1412         RefPtr<Pair> pair = Pair::create(parsedValue1.release(), parsedValue2.release());
1413         RefPtr<CSSPrimitiveValue> val = primitiveValueCache()->createValue(pair.release());
1414         addProperty(propId, val.release(), important);
1415         return true;
1416     }
1417     case CSSPropertyBorderRadius:
1418     case CSSPropertyWebkitBorderRadius:
1419         return parseBorderRadius(propId, important);
1420     case CSSPropertyOutlineOffset:
1421         validPrimitive = validUnit(value, FLength | FPercent, m_strict);
1422         break;
1423     case CSSPropertyTextShadow: // CSS2 property, dropped in CSS2.1, back in CSS3, so treat as CSS3
1424     case CSSPropertyBoxShadow:
1425     case CSSPropertyWebkitBoxShadow:
1426         if (id == CSSValueNone)
1427             validPrimitive = true;
1428         else
1429             return parseShadow(propId, important);
1430         break;
1431     case CSSPropertyWebkitBoxReflect:
1432         if (id == CSSValueNone)
1433             validPrimitive = true;
1434         else
1435             return parseReflect(propId, important);
1436         break;
1437     case CSSPropertyOpacity:
1438         validPrimitive = validUnit(value, FNumber, m_strict);
1439         break;
1440     case CSSPropertyWebkitBoxAlign:
1441         if (id == CSSValueStretch || id == CSSValueStart || id == CSSValueEnd ||
1442             id == CSSValueCenter || id == CSSValueBaseline)
1443             validPrimitive = true;
1444         break;
1445     case CSSPropertyWebkitBoxDirection:
1446         if (id == CSSValueNormal || id == CSSValueReverse)
1447             validPrimitive = true;
1448         break;
1449     case CSSPropertyWebkitBoxLines:
1450         if (id == CSSValueSingle || id == CSSValueMultiple)
1451             validPrimitive = true;
1452         break;
1453     case CSSPropertyWebkitBoxOrient:
1454         if (id == CSSValueHorizontal || id == CSSValueVertical ||
1455             id == CSSValueInlineAxis || id == CSSValueBlockAxis)
1456             validPrimitive = true;
1457         break;
1458     case CSSPropertyWebkitBoxPack:
1459         if (id == CSSValueStart || id == CSSValueEnd ||
1460             id == CSSValueCenter || id == CSSValueJustify)
1461             validPrimitive = true;
1462         break;
1463     case CSSPropertyWebkitBoxFlex:
1464         validPrimitive = validUnit(value, FNumber, m_strict);
1465         break;
1466     case CSSPropertyWebkitBoxFlexGroup:
1467     case CSSPropertyWebkitBoxOrdinalGroup:
1468         validPrimitive = validUnit(value, FInteger | FNonNeg, true);
1469         break;
1470     case CSSPropertyBoxSizing:
1471         validPrimitive = id == CSSValueBorderBox || id == CSSValueContentBox;
1472         break;
1473     case CSSPropertyWebkitColorCorrection:
1474         validPrimitive = id == CSSValueSrgb || id == CSSValueDefault;
1475         break;
1476     case CSSPropertyWebkitMarquee: {
1477         const int properties[5] = { CSSPropertyWebkitMarqueeDirection, CSSPropertyWebkitMarqueeIncrement,
1478                                     CSSPropertyWebkitMarqueeRepetition,
1479                                     CSSPropertyWebkitMarqueeStyle, CSSPropertyWebkitMarqueeSpeed };
1480         return parseShorthand(propId, properties, 5, important);
1481     }
1482     case CSSPropertyWebkitMarqueeDirection:
1483         if (id == CSSValueForwards || id == CSSValueBackwards || id == CSSValueAhead ||
1484             id == CSSValueReverse || id == CSSValueLeft || id == CSSValueRight || id == CSSValueDown ||
1485             id == CSSValueUp || id == CSSValueAuto)
1486             validPrimitive = true;
1487         break;
1488     case CSSPropertyWebkitMarqueeIncrement:
1489         if (id == CSSValueSmall || id == CSSValueLarge || id == CSSValueMedium)
1490             validPrimitive = true;
1491         else
1492             validPrimitive = validUnit(value, FLength | FPercent, m_strict);
1493         break;
1494     case CSSPropertyWebkitMarqueeStyle:
1495         if (id == CSSValueNone || id == CSSValueSlide || id == CSSValueScroll || id == CSSValueAlternate)
1496             validPrimitive = true;
1497         break;
1498     case CSSPropertyWebkitMarqueeRepetition:
1499         if (id == CSSValueInfinite)
1500             validPrimitive = true;
1501         else
1502             validPrimitive = validUnit(value, FInteger | FNonNeg, m_strict);
1503         break;
1504     case CSSPropertyWebkitMarqueeSpeed:
1505         if (id == CSSValueNormal || id == CSSValueSlow || id == CSSValueFast)
1506             validPrimitive = true;
1507         else
1508             validPrimitive = validUnit(value, FTime | FInteger | FNonNeg, m_strict);
1509         break;
1510 #if ENABLE(WCSS)
1511     case CSSPropertyWapMarqueeDir:
1512         if (id == CSSValueLtr || id == CSSValueRtl)
1513             validPrimitive = true;
1514         break;
1515     case CSSPropertyWapMarqueeStyle:
1516         if (id == CSSValueNone || id == CSSValueSlide || id == CSSValueScroll || id == CSSValueAlternate)
1517             validPrimitive = true;
1518         break;
1519     case CSSPropertyWapMarqueeLoop:
1520         if (id == CSSValueInfinite)
1521             validPrimitive = true;
1522         else
1523             validPrimitive = validUnit(value, FInteger | FNonNeg, m_strict);
1524         break;
1525     case CSSPropertyWapMarqueeSpeed:
1526         if (id == CSSValueNormal || id == CSSValueSlow || id == CSSValueFast)
1527             validPrimitive = true;
1528         else
1529             validPrimitive = validUnit(value, FTime | FInteger | FNonNeg, m_strict);
1530         break;
1531 #endif
1532     case CSSPropertyWebkitUserDrag: // auto | none | element
1533         if (id == CSSValueAuto || id == CSSValueNone || id == CSSValueElement)
1534             validPrimitive = true;
1535         break;
1536     case CSSPropertyWebkitUserModify: // read-only | read-write
1537         if (id == CSSValueReadOnly || id == CSSValueReadWrite || id == CSSValueReadWritePlaintextOnly)
1538             validPrimitive = true;
1539         break;
1540     case CSSPropertyWebkitUserSelect: // auto | none | text
1541         if (id == CSSValueAuto || id == CSSValueNone || id == CSSValueText)
1542             validPrimitive = true;
1543         break;
1544     case CSSPropertyTextOverflow: // clip | ellipsis
1545         if (id == CSSValueClip || id == CSSValueEllipsis)
1546             validPrimitive = true;
1547         break;
1548     case CSSPropertyWebkitTransform:
1549         if (id == CSSValueNone)
1550             validPrimitive = true;
1551         else {
1552             PassRefPtr<CSSValue> val = parseTransform();
1553             if (val) {
1554                 addProperty(propId, val, important);
1555                 return true;
1556             }
1557             return false;
1558         }
1559         break;
1560     case CSSPropertyWebkitTransformOrigin:
1561     case CSSPropertyWebkitTransformOriginX:
1562     case CSSPropertyWebkitTransformOriginY:
1563     case CSSPropertyWebkitTransformOriginZ: {
1564         RefPtr<CSSValue> val1;
1565         RefPtr<CSSValue> val2;
1566         RefPtr<CSSValue> val3;
1567         int propId1, propId2, propId3;
1568         if (parseTransformOrigin(propId, propId1, propId2, propId3, val1, val2, val3)) {
1569             addProperty(propId1, val1.release(), important);
1570             if (val2)
1571                 addProperty(propId2, val2.release(), important);
1572             if (val3)
1573                 addProperty(propId3, val3.release(), important);
1574             return true;
1575         }
1576         return false;
1577     }
1578     case CSSPropertyWebkitTransformStyle:
1579         if (value->id == CSSValueFlat || value->id == CSSValuePreserve3d)
1580             validPrimitive = true;
1581         break;
1582     case CSSPropertyWebkitBackfaceVisibility:
1583         if (value->id == CSSValueVisible || value->id == CSSValueHidden)
1584             validPrimitive = true;
1585         break;
1586     case CSSPropertyWebkitPerspective:
1587         if (id == CSSValueNone)
1588             validPrimitive = true;
1589         else {
1590             // Accepting valueless numbers is a quirk of the -webkit prefixed version of the property.
1591             if (validUnit(value, FNumber | FLength | FNonNeg, m_strict)) {
1592                 RefPtr<CSSValue> val = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit);
1593                 if (val) {
1594                     addProperty(propId, val.release(), important);
1595                     return true;
1596                 }
1597                 return false;
1598             }
1599         }
1600         break;
1601     case CSSPropertyWebkitPerspectiveOrigin:
1602     case CSSPropertyWebkitPerspectiveOriginX:
1603     case CSSPropertyWebkitPerspectiveOriginY: {
1604         RefPtr<CSSValue> val1;
1605         RefPtr<CSSValue> val2;
1606         int propId1, propId2;
1607         if (parsePerspectiveOrigin(propId, propId1, propId2, val1, val2)) {
1608             addProperty(propId1, val1.release(), important);
1609             if (val2)
1610                 addProperty(propId2, val2.release(), important);
1611             return true;
1612         }
1613         return false;
1614     }
1615     case CSSPropertyWebkitAnimationDelay:
1616     case CSSPropertyWebkitAnimationDirection:
1617     case CSSPropertyWebkitAnimationDuration:
1618     case CSSPropertyWebkitAnimationFillMode:
1619     case CSSPropertyWebkitAnimationName:
1620     case CSSPropertyWebkitAnimationPlayState:
1621     case CSSPropertyWebkitAnimationIterationCount:
1622     case CSSPropertyWebkitAnimationTimingFunction:
1623     case CSSPropertyWebkitTransitionDelay:
1624     case CSSPropertyWebkitTransitionDuration:
1625     case CSSPropertyWebkitTransitionTimingFunction:
1626     case CSSPropertyWebkitTransitionProperty: {
1627         RefPtr<CSSValue> val;
1628         if (parseAnimationProperty(propId, val)) {
1629             addProperty(propId, val.release(), important);
1630             return true;
1631         }
1632         return false;
1633     }
1634     case CSSPropertyWebkitMarginCollapse: {
1635         const int properties[2] = { CSSPropertyWebkitMarginBeforeCollapse,
1636             CSSPropertyWebkitMarginAfterCollapse };
1637         if (num == 1) {
1638             ShorthandScope scope(this, CSSPropertyWebkitMarginCollapse);
1639             if (!parseValue(properties[0], important))
1640                 return false;
1641             CSSValue* value = m_parsedProperties[m_numParsedProperties-1]->value();
1642             addProperty(properties[1], value, important);
1643             return true;
1644         }
1645         else if (num == 2) {
1646             ShorthandScope scope(this, CSSPropertyWebkitMarginCollapse);
1647             if (!parseValue(properties[0], important) || !parseValue(properties[1], important))
1648                 return false;
1649             return true;
1650         }
1651         return false;
1652     }
1653     case CSSPropertyWebkitMarginBeforeCollapse:
1654     case CSSPropertyWebkitMarginAfterCollapse:
1655     case CSSPropertyWebkitMarginTopCollapse:
1656     case CSSPropertyWebkitMarginBottomCollapse:
1657         if (id == CSSValueCollapse || id == CSSValueSeparate || id == CSSValueDiscard)
1658             validPrimitive = true;
1659         break;
1660     case CSSPropertyTextLineThroughMode:
1661     case CSSPropertyTextOverlineMode:
1662     case CSSPropertyTextUnderlineMode:
1663         if (id == CSSValueContinuous || id == CSSValueSkipWhiteSpace)
1664             validPrimitive = true;
1665         break;
1666     case CSSPropertyTextLineThroughStyle:
1667     case CSSPropertyTextOverlineStyle:
1668     case CSSPropertyTextUnderlineStyle:
1669         if (id == CSSValueNone || id == CSSValueSolid || id == CSSValueDouble ||
1670             id == CSSValueDashed || id == CSSValueDotDash || id == CSSValueDotDotDash ||
1671             id == CSSValueWave)
1672             validPrimitive = true;
1673         break;
1674     case CSSPropertyTextRendering: // auto | optimizeSpeed | optimizeLegibility | geometricPrecision
1675         if (id == CSSValueAuto || id == CSSValueOptimizespeed || id == CSSValueOptimizelegibility
1676             || id == CSSValueGeometricprecision)
1677             validPrimitive = true;
1678         break;
1679     case CSSPropertyTextLineThroughWidth:
1680     case CSSPropertyTextOverlineWidth:
1681     case CSSPropertyTextUnderlineWidth:
1682         if (id == CSSValueAuto || id == CSSValueNormal || id == CSSValueThin ||
1683             id == CSSValueMedium || id == CSSValueThick)
1684             validPrimitive = true;
1685         else
1686             validPrimitive = !id && validUnit(value, FNumber | FLength | FPercent, m_strict);
1687         break;
1688     case CSSPropertyResize: // none | both | horizontal | vertical | auto
1689         if (id == CSSValueNone || id == CSSValueBoth || id == CSSValueHorizontal || id == CSSValueVertical || id == CSSValueAuto)
1690             validPrimitive = true;
1691         break;
1692     case CSSPropertyWebkitColumnCount:
1693         if (id == CSSValueAuto)
1694             validPrimitive = true;
1695         else
1696             validPrimitive = !id && validUnit(value, FInteger | FNonNeg, false);
1697         break;
1698     case CSSPropertyWebkitColumnGap:         // normal | <length>
1699         if (id == CSSValueNormal)
1700             validPrimitive = true;
1701         else
1702             validPrimitive = validUnit(value, FLength | FNonNeg, m_strict);
1703         break;
1704     case CSSPropertyWebkitColumnSpan:        // all | 1
1705         if (id == CSSValueAll)
1706             validPrimitive = true;
1707         else
1708             validPrimitive = validUnit(value, FNumber | FNonNeg, m_strict) && value->fValue == 1;
1709         break;
1710     case CSSPropertyWebkitColumnWidth:         // auto | <length>
1711         if (id == CSSValueAuto)
1712             validPrimitive = true;
1713         else // Always parse this property in strict mode, since it would be ambiguous otherwise when used in the 'columns' shorthand property.
1714             validPrimitive = validUnit(value, FLength, true);
1715         break;
1716     case CSSPropertyPointerEvents:
1717         // none | visiblePainted | visibleFill | visibleStroke | visible |
1718         // painted | fill | stroke | auto | all | inherit
1719         if (id == CSSValueVisible || id == CSSValueNone || id == CSSValueAll || id == CSSValueAuto ||
1720             (id >= CSSValueVisiblepainted && id <= CSSValueStroke))
1721             validPrimitive = true;
1722         break;
1723 
1724     // End of CSS3 properties
1725 
1726     // Apple specific properties.  These will never be standardized and are purely to
1727     // support custom WebKit-based Apple applications.
1728     case CSSPropertyWebkitLineClamp:
1729         // When specifying number of lines, don't allow 0 as a valid value
1730         // When specifying either type of unit, require non-negative integers
1731         validPrimitive = (!id && (value->unit == CSSPrimitiveValue::CSS_PERCENTAGE || value->fValue) && validUnit(value, FInteger | FPercent | FNonNeg, false));
1732         break;
1733     case CSSPropertyWebkitTextSizeAdjust:
1734         if (id == CSSValueAuto || id == CSSValueNone)
1735             validPrimitive = true;
1736         break;
1737     case CSSPropertyWebkitRtlOrdering:
1738         if (id == CSSValueLogical || id == CSSValueVisual)
1739             validPrimitive = true;
1740         break;
1741 
1742     case CSSPropertyWebkitFontSizeDelta:           // <length>
1743         validPrimitive = validUnit(value, FLength, m_strict);
1744         break;
1745 
1746     case CSSPropertyWebkitNbspMode:     // normal | space
1747         if (id == CSSValueNormal || id == CSSValueSpace)
1748             validPrimitive = true;
1749         break;
1750 
1751     case CSSPropertyWebkitLineBreak:   // normal | after-white-space
1752         if (id == CSSValueNormal || id == CSSValueAfterWhiteSpace)
1753             validPrimitive = true;
1754         break;
1755 
1756     case CSSPropertyWebkitMatchNearestMailBlockquoteColor:   // normal | match
1757         if (id == CSSValueNormal || id == CSSValueMatch)
1758             validPrimitive = true;
1759         break;
1760 
1761     case CSSPropertyWebkitHighlight:
1762         if (id == CSSValueNone || value->unit == CSSPrimitiveValue::CSS_STRING)
1763             validPrimitive = true;
1764         break;
1765 
1766     case CSSPropertyWebkitHyphens:
1767         if (id == CSSValueNone || id == CSSValueManual || id == CSSValueAuto)
1768             validPrimitive = true;
1769         break;
1770 
1771     case CSSPropertyWebkitHyphenateCharacter:
1772         if (id == CSSValueAuto || value->unit == CSSPrimitiveValue::CSS_STRING)
1773             validPrimitive = true;
1774         break;
1775 
1776     case CSSPropertyWebkitHyphenateLimitBefore:
1777     case CSSPropertyWebkitHyphenateLimitAfter:
1778         if (id == CSSValueAuto || validUnit(value, FInteger | FNonNeg, true))
1779             validPrimitive = true;
1780         break;
1781 
1782     case CSSPropertyWebkitLocale:
1783         if (id == CSSValueAuto || value->unit == CSSPrimitiveValue::CSS_STRING)
1784             validPrimitive = true;
1785         break;
1786 
1787     case CSSPropertyWebkitBorderFit:
1788         if (id == CSSValueBorder || id == CSSValueLines)
1789             validPrimitive = true;
1790         break;
1791 
1792     case CSSPropertyWebkitTextSecurity:
1793         // disc | circle | square | none | inherit
1794         if (id == CSSValueDisc || id == CSSValueCircle || id == CSSValueSquare|| id == CSSValueNone)
1795             validPrimitive = true;
1796         break;
1797 
1798     case CSSPropertyWebkitFontSmoothing:
1799         if (id == CSSValueAuto || id == CSSValueNone
1800             || id == CSSValueAntialiased || id == CSSValueSubpixelAntialiased)
1801             validPrimitive = true;
1802         break;
1803 
1804 #if ENABLE(DASHBOARD_SUPPORT)
1805     case CSSPropertyWebkitDashboardRegion: // <dashboard-region> | <dashboard-region>
1806         if (value->unit == CSSParserValue::Function || id == CSSValueNone)
1807             return parseDashboardRegions(propId, important);
1808         break;
1809 #endif
1810     // End Apple-specific properties
1811 
1812         /* shorthand properties */
1813     case CSSPropertyBackground: {
1814         // Position must come before color in this array because a plain old "0" is a legal color
1815         // in quirks mode but it's usually the X coordinate of a position.
1816         // FIXME: Add CSSPropertyBackgroundSize to the shorthand.
1817         const int properties[] = { CSSPropertyBackgroundImage, CSSPropertyBackgroundRepeat,
1818                                    CSSPropertyBackgroundAttachment, CSSPropertyBackgroundPosition, CSSPropertyBackgroundOrigin,
1819                                    CSSPropertyBackgroundClip, CSSPropertyBackgroundColor };
1820         return parseFillShorthand(propId, properties, 7, important);
1821     }
1822     case CSSPropertyWebkitMask: {
1823         const int properties[] = { CSSPropertyWebkitMaskImage, CSSPropertyWebkitMaskRepeat,
1824                                    CSSPropertyWebkitMaskAttachment, CSSPropertyWebkitMaskPosition,
1825                                    CSSPropertyWebkitMaskOrigin, CSSPropertyWebkitMaskClip };
1826         return parseFillShorthand(propId, properties, 6, important);
1827     }
1828     case CSSPropertyBorder:
1829         // [ 'border-width' || 'border-style' || <color> ] | inherit
1830     {
1831         const int properties[3] = { CSSPropertyBorderWidth, CSSPropertyBorderStyle,
1832                                     CSSPropertyBorderColor };
1833         return parseShorthand(propId, properties, 3, important);
1834     }
1835     case CSSPropertyBorderTop:
1836         // [ 'border-top-width' || 'border-style' || <color> ] | inherit
1837     {
1838         const int properties[3] = { CSSPropertyBorderTopWidth, CSSPropertyBorderTopStyle,
1839                                     CSSPropertyBorderTopColor};
1840         return parseShorthand(propId, properties, 3, important);
1841     }
1842     case CSSPropertyBorderRight:
1843         // [ 'border-right-width' || 'border-style' || <color> ] | inherit
1844     {
1845         const int properties[3] = { CSSPropertyBorderRightWidth, CSSPropertyBorderRightStyle,
1846                                     CSSPropertyBorderRightColor };
1847         return parseShorthand(propId, properties, 3, important);
1848     }
1849     case CSSPropertyBorderBottom:
1850         // [ 'border-bottom-width' || 'border-style' || <color> ] | inherit
1851     {
1852         const int properties[3] = { CSSPropertyBorderBottomWidth, CSSPropertyBorderBottomStyle,
1853                                     CSSPropertyBorderBottomColor };
1854         return parseShorthand(propId, properties, 3, important);
1855     }
1856     case CSSPropertyBorderLeft:
1857         // [ 'border-left-width' || 'border-style' || <color> ] | inherit
1858     {
1859         const int properties[3] = { CSSPropertyBorderLeftWidth, CSSPropertyBorderLeftStyle,
1860                                     CSSPropertyBorderLeftColor };
1861         return parseShorthand(propId, properties, 3, important);
1862     }
1863     case CSSPropertyWebkitBorderStart:
1864     {
1865         const int properties[3] = { CSSPropertyWebkitBorderStartWidth, CSSPropertyWebkitBorderStartStyle,
1866             CSSPropertyWebkitBorderStartColor };
1867         return parseShorthand(propId, properties, 3, important);
1868     }
1869     case CSSPropertyWebkitBorderEnd:
1870     {
1871         const int properties[3] = { CSSPropertyWebkitBorderEndWidth, CSSPropertyWebkitBorderEndStyle,
1872             CSSPropertyWebkitBorderEndColor };
1873         return parseShorthand(propId, properties, 3, important);
1874     }
1875     case CSSPropertyWebkitBorderBefore:
1876     {
1877         const int properties[3] = { CSSPropertyWebkitBorderBeforeWidth, CSSPropertyWebkitBorderBeforeStyle,
1878             CSSPropertyWebkitBorderBeforeColor };
1879         return parseShorthand(propId, properties, 3, important);
1880     }
1881     case CSSPropertyWebkitBorderAfter:
1882     {
1883         const int properties[3] = { CSSPropertyWebkitBorderAfterWidth, CSSPropertyWebkitBorderAfterStyle,
1884             CSSPropertyWebkitBorderAfterColor };
1885         return parseShorthand(propId, properties, 3, important);
1886     }
1887     case CSSPropertyOutline:
1888         // [ 'outline-color' || 'outline-style' || 'outline-width' ] | inherit
1889     {
1890         const int properties[3] = { CSSPropertyOutlineWidth, CSSPropertyOutlineStyle,
1891                                     CSSPropertyOutlineColor };
1892         return parseShorthand(propId, properties, 3, important);
1893     }
1894     case CSSPropertyBorderColor:
1895         // <color>{1,4} | inherit
1896     {
1897         const int properties[4] = { CSSPropertyBorderTopColor, CSSPropertyBorderRightColor,
1898                                     CSSPropertyBorderBottomColor, CSSPropertyBorderLeftColor };
1899         return parse4Values(propId, properties, important);
1900     }
1901     case CSSPropertyBorderWidth:
1902         // <border-width>{1,4} | inherit
1903     {
1904         const int properties[4] = { CSSPropertyBorderTopWidth, CSSPropertyBorderRightWidth,
1905                                     CSSPropertyBorderBottomWidth, CSSPropertyBorderLeftWidth };
1906         return parse4Values(propId, properties, important);
1907     }
1908     case CSSPropertyBorderStyle:
1909         // <border-style>{1,4} | inherit
1910     {
1911         const int properties[4] = { CSSPropertyBorderTopStyle, CSSPropertyBorderRightStyle,
1912                                     CSSPropertyBorderBottomStyle, CSSPropertyBorderLeftStyle };
1913         return parse4Values(propId, properties, important);
1914     }
1915     case CSSPropertyMargin:
1916         // <margin-width>{1,4} | inherit
1917     {
1918         const int properties[4] = { CSSPropertyMarginTop, CSSPropertyMarginRight,
1919                                     CSSPropertyMarginBottom, CSSPropertyMarginLeft };
1920         return parse4Values(propId, properties, important);
1921     }
1922     case CSSPropertyPadding:
1923         // <padding-width>{1,4} | inherit
1924     {
1925         const int properties[4] = { CSSPropertyPaddingTop, CSSPropertyPaddingRight,
1926                                     CSSPropertyPaddingBottom, CSSPropertyPaddingLeft };
1927         return parse4Values(propId, properties, important);
1928     }
1929     case CSSPropertyFont:
1930         // [ [ 'font-style' || 'font-variant' || 'font-weight' ]? 'font-size' [ / 'line-height' ]?
1931         // 'font-family' ] | caption | icon | menu | message-box | small-caption | status-bar | inherit
1932         if (id >= CSSValueCaption && id <= CSSValueStatusBar)
1933             validPrimitive = true;
1934         else
1935             return parseFont(important);
1936         break;
1937     case CSSPropertyListStyle:
1938     {
1939         const int properties[3] = { CSSPropertyListStyleType, CSSPropertyListStylePosition,
1940                                     CSSPropertyListStyleImage };
1941         return parseShorthand(propId, properties, 3, important);
1942     }
1943     case CSSPropertyWebkitColumns: {
1944         const int properties[2] = { CSSPropertyWebkitColumnWidth, CSSPropertyWebkitColumnCount };
1945         return parseShorthand(propId, properties, 2, important);
1946     }
1947     case CSSPropertyWebkitColumnRule: {
1948         const int properties[3] = { CSSPropertyWebkitColumnRuleWidth, CSSPropertyWebkitColumnRuleStyle,
1949                                     CSSPropertyWebkitColumnRuleColor };
1950         return parseShorthand(propId, properties, 3, important);
1951     }
1952     case CSSPropertyWebkitTextStroke: {
1953         const int properties[2] = { CSSPropertyWebkitTextStrokeWidth, CSSPropertyWebkitTextStrokeColor };
1954         return parseShorthand(propId, properties, 2, important);
1955     }
1956     case CSSPropertyWebkitAnimation:
1957         return parseAnimationShorthand(important);
1958     case CSSPropertyWebkitTransition:
1959         return parseTransitionShorthand(important);
1960     case CSSPropertyInvalid:
1961         return false;
1962     case CSSPropertyPage:
1963         return parsePage(propId, important);
1964     case CSSPropertyFontStretch:
1965     case CSSPropertyTextLineThrough:
1966     case CSSPropertyTextOverline:
1967     case CSSPropertyTextUnderline:
1968         return false;
1969 #if ENABLE(WCSS)
1970     case CSSPropertyWapInputFormat:
1971         validPrimitive = true;
1972         break;
1973     case CSSPropertyWapInputRequired:
1974         parsedValue = parseWCSSInputProperty();
1975         break;
1976 #endif
1977 
1978     // CSS Text Layout Module Level 3: Vertical writing support
1979     case CSSPropertyWebkitWritingMode:
1980         if (id >= CSSValueHorizontalTb && id <= CSSValueHorizontalBt)
1981             validPrimitive = true;
1982         break;
1983 
1984     case CSSPropertyWebkitTextCombine:
1985         if (id == CSSValueNone || id == CSSValueHorizontal)
1986             validPrimitive = true;
1987         break;
1988 
1989     case CSSPropertyWebkitTextEmphasis: {
1990         const int properties[] = { CSSPropertyWebkitTextEmphasisStyle, CSSPropertyWebkitTextEmphasisColor };
1991         return parseShorthand(propId, properties, WTF_ARRAY_LENGTH(properties), important);
1992     }
1993 
1994     case CSSPropertyWebkitTextEmphasisPosition:
1995         if (id == CSSValueOver || id == CSSValueUnder)
1996             validPrimitive = true;
1997         break;
1998 
1999     case CSSPropertyWebkitTextEmphasisStyle:
2000         return parseTextEmphasisStyle(important);
2001 
2002     case CSSPropertyWebkitTextOrientation:
2003         // FIXME: For now just support upright and vertical-right.
2004         if (id == CSSValueVerticalRight || id == CSSValueUpright)
2005             validPrimitive = true;
2006         break;
2007 
2008     case CSSPropertyWebkitLineBoxContain:
2009         if (id == CSSValueNone)
2010             validPrimitive = true;
2011         else
2012             return parseLineBoxContain(important);
2013         break;
2014 
2015 #if ENABLE(SVG)
2016     default:
2017         return parseSVGValue(propId, important);
2018 #endif
2019     }
2020 
2021     if (validPrimitive) {
2022         if (id != 0)
2023             parsedValue = primitiveValueCache()->createIdentifierValue(id);
2024         else if (value->unit == CSSPrimitiveValue::CSS_STRING)
2025             parsedValue = primitiveValueCache()->createValue(value->string, (CSSPrimitiveValue::UnitTypes) value->unit);
2026         else if (value->unit >= CSSPrimitiveValue::CSS_NUMBER && value->unit <= CSSPrimitiveValue::CSS_KHZ)
2027             parsedValue = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes) value->unit);
2028         else if (value->unit >= CSSPrimitiveValue::CSS_TURN && value->unit <= CSSPrimitiveValue::CSS_REMS)
2029             parsedValue = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes) value->unit);
2030         else if (value->unit >= CSSParserValue::Q_EMS)
2031             parsedValue = CSSQuirkPrimitiveValue::create(value->fValue, CSSPrimitiveValue::CSS_EMS);
2032         m_valueList->next();
2033     }
2034     if (parsedValue) {
2035         if (!m_valueList->current() || inShorthand()) {
2036             addProperty(propId, parsedValue.release(), important);
2037             return true;
2038         }
2039     }
2040     return false;
2041 }
2042 
2043 #if ENABLE(WCSS)
parseWCSSInputProperty()2044 PassRefPtr<CSSValue> CSSParser::parseWCSSInputProperty()
2045 {
2046     RefPtr<CSSValue> parsedValue = 0;
2047     CSSParserValue* value = m_valueList->current();
2048     String inputProperty;
2049     if (value->unit == CSSPrimitiveValue::CSS_STRING || value->unit == CSSPrimitiveValue::CSS_IDENT)
2050         inputProperty = String(value->string);
2051 
2052     if (!inputProperty.isEmpty())
2053        parsedValue = primitiveValueCache()->createValue(inputProperty, CSSPrimitiveValue::CSS_STRING);
2054 
2055     while (m_valueList->next()) {
2056     // pass all other values, if any. If we don't do this,
2057     // the parser will think that it's not done and won't process this property
2058     }
2059 
2060     return parsedValue;
2061 }
2062 #endif
2063 
addFillValue(RefPtr<CSSValue> & lval,PassRefPtr<CSSValue> rval)2064 void CSSParser::addFillValue(RefPtr<CSSValue>& lval, PassRefPtr<CSSValue> rval)
2065 {
2066     if (lval) {
2067         if (lval->isValueList())
2068             static_cast<CSSValueList*>(lval.get())->append(rval);
2069         else {
2070             PassRefPtr<CSSValue> oldlVal(lval.release());
2071             PassRefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
2072             list->append(oldlVal);
2073             list->append(rval);
2074             lval = list;
2075         }
2076     }
2077     else
2078         lval = rval;
2079 }
2080 
parseBackgroundClip(CSSParserValue * parserValue,RefPtr<CSSValue> & cssValue,CSSPrimitiveValueCache * primitiveValueCache)2081 static bool parseBackgroundClip(CSSParserValue* parserValue, RefPtr<CSSValue>& cssValue, CSSPrimitiveValueCache* primitiveValueCache)
2082 {
2083     if (parserValue->id == CSSValueBorderBox || parserValue->id == CSSValuePaddingBox
2084         || parserValue->id == CSSValueContentBox || parserValue->id == CSSValueWebkitText) {
2085         cssValue = primitiveValueCache->createIdentifierValue(parserValue->id);
2086         return true;
2087     }
2088     return false;
2089 }
2090 
2091 const int cMaxFillProperties = 9;
2092 
parseFillShorthand(int propId,const int * properties,int numProperties,bool important)2093 bool CSSParser::parseFillShorthand(int propId, const int* properties, int numProperties, bool important)
2094 {
2095     ASSERT(numProperties <= cMaxFillProperties);
2096     if (numProperties > cMaxFillProperties)
2097         return false;
2098 
2099     ShorthandScope scope(this, propId);
2100 
2101     bool parsedProperty[cMaxFillProperties] = { false };
2102     RefPtr<CSSValue> values[cMaxFillProperties];
2103     RefPtr<CSSValue> clipValue;
2104     RefPtr<CSSValue> positionYValue;
2105     RefPtr<CSSValue> repeatYValue;
2106     bool foundClip = false;
2107     int i;
2108 
2109     while (m_valueList->current()) {
2110         CSSParserValue* val = m_valueList->current();
2111         if (val->unit == CSSParserValue::Operator && val->iValue == ',') {
2112             // We hit the end.  Fill in all remaining values with the initial value.
2113             m_valueList->next();
2114             for (i = 0; i < numProperties; ++i) {
2115                 if (properties[i] == CSSPropertyBackgroundColor && parsedProperty[i])
2116                     // Color is not allowed except as the last item in a list for backgrounds.
2117                     // Reject the entire property.
2118                     return false;
2119 
2120                 if (!parsedProperty[i] && properties[i] != CSSPropertyBackgroundColor) {
2121                     addFillValue(values[i], CSSInitialValue::createImplicit());
2122                     if (properties[i] == CSSPropertyBackgroundPosition || properties[i] == CSSPropertyWebkitMaskPosition)
2123                         addFillValue(positionYValue, CSSInitialValue::createImplicit());
2124                     if (properties[i] == CSSPropertyBackgroundRepeat || properties[i] == CSSPropertyWebkitMaskRepeat)
2125                         addFillValue(repeatYValue, CSSInitialValue::createImplicit());
2126                     if ((properties[i] == CSSPropertyBackgroundOrigin || properties[i] == CSSPropertyWebkitMaskOrigin) && !parsedProperty[i]) {
2127                         // If background-origin wasn't present, then reset background-clip also.
2128                         addFillValue(clipValue, CSSInitialValue::createImplicit());
2129                     }
2130                 }
2131                 parsedProperty[i] = false;
2132             }
2133             if (!m_valueList->current())
2134                 break;
2135         }
2136 
2137         bool found = false;
2138         for (i = 0; !found && i < numProperties; ++i) {
2139             if (!parsedProperty[i]) {
2140                 RefPtr<CSSValue> val1;
2141                 RefPtr<CSSValue> val2;
2142                 int propId1, propId2;
2143                 CSSParserValue* parserValue = m_valueList->current();
2144                 if (parseFillProperty(properties[i], propId1, propId2, val1, val2)) {
2145                     parsedProperty[i] = found = true;
2146                     addFillValue(values[i], val1.release());
2147                     if (properties[i] == CSSPropertyBackgroundPosition || properties[i] == CSSPropertyWebkitMaskPosition)
2148                         addFillValue(positionYValue, val2.release());
2149                     if (properties[i] == CSSPropertyBackgroundRepeat || properties[i] == CSSPropertyWebkitMaskRepeat)
2150                         addFillValue(repeatYValue, val2.release());
2151                     if (properties[i] == CSSPropertyBackgroundOrigin || properties[i] == CSSPropertyWebkitMaskOrigin) {
2152                         // Reparse the value as a clip, and see if we succeed.
2153                         if (parseBackgroundClip(parserValue, val1, primitiveValueCache()))
2154                             addFillValue(clipValue, val1.release()); // The property parsed successfully.
2155                         else
2156                             addFillValue(clipValue, CSSInitialValue::createImplicit()); // Some value was used for origin that is not supported by clip. Just reset clip instead.
2157                     }
2158                     if (properties[i] == CSSPropertyBackgroundClip || properties[i] == CSSPropertyWebkitMaskClip) {
2159                         // Update clipValue
2160                         addFillValue(clipValue, val1.release());
2161                         foundClip = true;
2162                     }
2163                 }
2164             }
2165         }
2166 
2167         // if we didn't find at least one match, this is an
2168         // invalid shorthand and we have to ignore it
2169         if (!found)
2170             return false;
2171     }
2172 
2173     // Fill in any remaining properties with the initial value.
2174     for (i = 0; i < numProperties; ++i) {
2175         if (!parsedProperty[i]) {
2176             addFillValue(values[i], CSSInitialValue::createImplicit());
2177             if (properties[i] == CSSPropertyBackgroundPosition || properties[i] == CSSPropertyWebkitMaskPosition)
2178                 addFillValue(positionYValue, CSSInitialValue::createImplicit());
2179             if (properties[i] == CSSPropertyBackgroundRepeat || properties[i] == CSSPropertyWebkitMaskRepeat)
2180                 addFillValue(repeatYValue, CSSInitialValue::createImplicit());
2181             if ((properties[i] == CSSPropertyBackgroundOrigin || properties[i] == CSSPropertyWebkitMaskOrigin) && !parsedProperty[i]) {
2182                 // If background-origin wasn't present, then reset background-clip also.
2183                 addFillValue(clipValue, CSSInitialValue::createImplicit());
2184             }
2185         }
2186     }
2187 
2188     // Now add all of the properties we found.
2189     for (i = 0; i < numProperties; i++) {
2190         if (properties[i] == CSSPropertyBackgroundPosition) {
2191             addProperty(CSSPropertyBackgroundPositionX, values[i].release(), important);
2192             // it's OK to call positionYValue.release() since we only see CSSPropertyBackgroundPosition once
2193             addProperty(CSSPropertyBackgroundPositionY, positionYValue.release(), important);
2194         } else if (properties[i] == CSSPropertyWebkitMaskPosition) {
2195             addProperty(CSSPropertyWebkitMaskPositionX, values[i].release(), important);
2196             // it's OK to call positionYValue.release() since we only see CSSPropertyWebkitMaskPosition once
2197             addProperty(CSSPropertyWebkitMaskPositionY, positionYValue.release(), important);
2198         } else if (properties[i] == CSSPropertyBackgroundRepeat) {
2199             addProperty(CSSPropertyBackgroundRepeatX, values[i].release(), important);
2200             // it's OK to call repeatYValue.release() since we only see CSSPropertyBackgroundPosition once
2201             addProperty(CSSPropertyBackgroundRepeatY, repeatYValue.release(), important);
2202         } else if (properties[i] == CSSPropertyWebkitMaskRepeat) {
2203             addProperty(CSSPropertyWebkitMaskRepeatX, values[i].release(), important);
2204             // it's OK to call repeatYValue.release() since we only see CSSPropertyBackgroundPosition once
2205             addProperty(CSSPropertyWebkitMaskRepeatY, repeatYValue.release(), important);
2206         } else if ((properties[i] == CSSPropertyBackgroundClip || properties[i] == CSSPropertyWebkitMaskClip) && !foundClip)
2207             // Value is already set while updating origin
2208             continue;
2209         else
2210             addProperty(properties[i], values[i].release(), important);
2211 
2212         // Add in clip values when we hit the corresponding origin property.
2213         if (properties[i] == CSSPropertyBackgroundOrigin && !foundClip)
2214             addProperty(CSSPropertyBackgroundClip, clipValue.release(), important);
2215         else if (properties[i] == CSSPropertyWebkitMaskOrigin && !foundClip)
2216             addProperty(CSSPropertyWebkitMaskClip, clipValue.release(), important);
2217     }
2218 
2219     return true;
2220 }
2221 
addAnimationValue(RefPtr<CSSValue> & lval,PassRefPtr<CSSValue> rval)2222 void CSSParser::addAnimationValue(RefPtr<CSSValue>& lval, PassRefPtr<CSSValue> rval)
2223 {
2224     if (lval) {
2225         if (lval->isValueList())
2226             static_cast<CSSValueList*>(lval.get())->append(rval);
2227         else {
2228             PassRefPtr<CSSValue> oldVal(lval.release());
2229             PassRefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
2230             list->append(oldVal);
2231             list->append(rval);
2232             lval = list;
2233         }
2234     }
2235     else
2236         lval = rval;
2237 }
2238 
parseAnimationShorthand(bool important)2239 bool CSSParser::parseAnimationShorthand(bool important)
2240 {
2241     const int properties[] = {  CSSPropertyWebkitAnimationName,
2242                                 CSSPropertyWebkitAnimationDuration,
2243                                 CSSPropertyWebkitAnimationTimingFunction,
2244                                 CSSPropertyWebkitAnimationDelay,
2245                                 CSSPropertyWebkitAnimationIterationCount,
2246                                 CSSPropertyWebkitAnimationDirection,
2247                                 CSSPropertyWebkitAnimationFillMode };
2248     const int numProperties = WTF_ARRAY_LENGTH(properties);
2249 
2250     ShorthandScope scope(this, CSSPropertyWebkitAnimation);
2251 
2252     bool parsedProperty[numProperties] = { false }; // compiler will repeat false as necessary
2253     RefPtr<CSSValue> values[numProperties];
2254 
2255     int i;
2256     while (m_valueList->current()) {
2257         CSSParserValue* val = m_valueList->current();
2258         if (val->unit == CSSParserValue::Operator && val->iValue == ',') {
2259             // We hit the end.  Fill in all remaining values with the initial value.
2260             m_valueList->next();
2261             for (i = 0; i < numProperties; ++i) {
2262                 if (!parsedProperty[i])
2263                     addAnimationValue(values[i], CSSInitialValue::createImplicit());
2264                 parsedProperty[i] = false;
2265             }
2266             if (!m_valueList->current())
2267                 break;
2268         }
2269 
2270         bool found = false;
2271         for (i = 0; !found && i < numProperties; ++i) {
2272             if (!parsedProperty[i]) {
2273                 RefPtr<CSSValue> val;
2274                 if (parseAnimationProperty(properties[i], val)) {
2275                     parsedProperty[i] = found = true;
2276                     addAnimationValue(values[i], val.release());
2277                 }
2278             }
2279         }
2280 
2281         // if we didn't find at least one match, this is an
2282         // invalid shorthand and we have to ignore it
2283         if (!found)
2284             return false;
2285     }
2286 
2287     // Fill in any remaining properties with the initial value.
2288     for (i = 0; i < numProperties; ++i) {
2289         if (!parsedProperty[i])
2290             addAnimationValue(values[i], CSSInitialValue::createImplicit());
2291     }
2292 
2293     // Now add all of the properties we found.
2294     for (i = 0; i < numProperties; i++)
2295         addProperty(properties[i], values[i].release(), important);
2296 
2297     return true;
2298 }
2299 
parseTransitionShorthand(bool important)2300 bool CSSParser::parseTransitionShorthand(bool important)
2301 {
2302     const int properties[] = { CSSPropertyWebkitTransitionProperty,
2303                                CSSPropertyWebkitTransitionDuration,
2304                                CSSPropertyWebkitTransitionTimingFunction,
2305                                CSSPropertyWebkitTransitionDelay };
2306     const int numProperties = WTF_ARRAY_LENGTH(properties);
2307 
2308     ShorthandScope scope(this, CSSPropertyWebkitTransition);
2309 
2310     bool parsedProperty[numProperties] = { false }; // compiler will repeat false as necessary
2311     RefPtr<CSSValue> values[numProperties];
2312 
2313     int i;
2314     while (m_valueList->current()) {
2315         CSSParserValue* val = m_valueList->current();
2316         if (val->unit == CSSParserValue::Operator && val->iValue == ',') {
2317             // We hit the end.  Fill in all remaining values with the initial value.
2318             m_valueList->next();
2319             for (i = 0; i < numProperties; ++i) {
2320                 if (!parsedProperty[i])
2321                     addAnimationValue(values[i], CSSInitialValue::createImplicit());
2322                 parsedProperty[i] = false;
2323             }
2324             if (!m_valueList->current())
2325                 break;
2326         }
2327 
2328         bool found = false;
2329         for (i = 0; !found && i < numProperties; ++i) {
2330             if (!parsedProperty[i]) {
2331                 RefPtr<CSSValue> val;
2332                 if (parseAnimationProperty(properties[i], val)) {
2333                     parsedProperty[i] = found = true;
2334                     addAnimationValue(values[i], val.release());
2335                 }
2336             }
2337         }
2338 
2339         // if we didn't find at least one match, this is an
2340         // invalid shorthand and we have to ignore it
2341         if (!found)
2342             return false;
2343     }
2344 
2345     // Fill in any remaining properties with the initial value.
2346     for (i = 0; i < numProperties; ++i) {
2347         if (!parsedProperty[i])
2348             addAnimationValue(values[i], CSSInitialValue::createImplicit());
2349     }
2350 
2351     // Now add all of the properties we found.
2352     for (i = 0; i < numProperties; i++)
2353         addProperty(properties[i], values[i].release(), important);
2354 
2355     return true;
2356 }
2357 
parseShorthand(int propId,const int * properties,int numProperties,bool important)2358 bool CSSParser::parseShorthand(int propId, const int *properties, int numProperties, bool important)
2359 {
2360     // We try to match as many properties as possible
2361     // We set up an array of booleans to mark which property has been found,
2362     // and we try to search for properties until it makes no longer any sense.
2363     ShorthandScope scope(this, propId);
2364 
2365     bool found = false;
2366     bool fnd[6]; // Trust me ;)
2367     for (int i = 0; i < numProperties; i++)
2368         fnd[i] = false;
2369 
2370     while (m_valueList->current()) {
2371         found = false;
2372         for (int propIndex = 0; !found && propIndex < numProperties; ++propIndex) {
2373             if (!fnd[propIndex]) {
2374                 if (parseValue(properties[propIndex], important))
2375                     fnd[propIndex] = found = true;
2376             }
2377         }
2378 
2379         // if we didn't find at least one match, this is an
2380         // invalid shorthand and we have to ignore it
2381         if (!found)
2382             return false;
2383     }
2384 
2385     // Fill in any remaining properties with the initial value.
2386     m_implicitShorthand = true;
2387     for (int i = 0; i < numProperties; ++i) {
2388         if (!fnd[i])
2389             addProperty(properties[i], CSSInitialValue::createImplicit(), important);
2390     }
2391     m_implicitShorthand = false;
2392 
2393     return true;
2394 }
2395 
parse4Values(int propId,const int * properties,bool important)2396 bool CSSParser::parse4Values(int propId, const int *properties,  bool important)
2397 {
2398     /* From the CSS 2 specs, 8.3
2399      * If there is only one value, it applies to all sides. If there are two values, the top and
2400      * bottom margins are set to the first value and the right and left margins are set to the second.
2401      * If there are three values, the top is set to the first value, the left and right are set to the
2402      * second, and the bottom is set to the third. If there are four values, they apply to the top,
2403      * right, bottom, and left, respectively.
2404      */
2405 
2406     int num = inShorthand() ? 1 : m_valueList->size();
2407 
2408     ShorthandScope scope(this, propId);
2409 
2410     // the order is top, right, bottom, left
2411     switch (num) {
2412         case 1: {
2413             if (!parseValue(properties[0], important))
2414                 return false;
2415             CSSValue *value = m_parsedProperties[m_numParsedProperties-1]->value();
2416             m_implicitShorthand = true;
2417             addProperty(properties[1], value, important);
2418             addProperty(properties[2], value, important);
2419             addProperty(properties[3], value, important);
2420             m_implicitShorthand = false;
2421             break;
2422         }
2423         case 2: {
2424             if (!parseValue(properties[0], important) || !parseValue(properties[1], important))
2425                 return false;
2426             CSSValue *value = m_parsedProperties[m_numParsedProperties-2]->value();
2427             m_implicitShorthand = true;
2428             addProperty(properties[2], value, important);
2429             value = m_parsedProperties[m_numParsedProperties-2]->value();
2430             addProperty(properties[3], value, important);
2431             m_implicitShorthand = false;
2432             break;
2433         }
2434         case 3: {
2435             if (!parseValue(properties[0], important) || !parseValue(properties[1], important) || !parseValue(properties[2], important))
2436                 return false;
2437             CSSValue *value = m_parsedProperties[m_numParsedProperties-2]->value();
2438             m_implicitShorthand = true;
2439             addProperty(properties[3], value, important);
2440             m_implicitShorthand = false;
2441             break;
2442         }
2443         case 4: {
2444             if (!parseValue(properties[0], important) || !parseValue(properties[1], important) ||
2445                 !parseValue(properties[2], important) || !parseValue(properties[3], important))
2446                 return false;
2447             break;
2448         }
2449         default: {
2450             return false;
2451         }
2452     }
2453 
2454     return true;
2455 }
2456 
2457 // auto | <identifier>
parsePage(int propId,bool important)2458 bool CSSParser::parsePage(int propId, bool important)
2459 {
2460     ASSERT(propId == CSSPropertyPage);
2461 
2462     if (m_valueList->size() != 1)
2463         return false;
2464 
2465     CSSParserValue* value = m_valueList->current();
2466     if (!value)
2467         return false;
2468 
2469     if (value->id == CSSValueAuto) {
2470         addProperty(propId, primitiveValueCache()->createIdentifierValue(value->id), important);
2471         return true;
2472     } else if (value->id == 0 && value->unit == CSSPrimitiveValue::CSS_IDENT) {
2473         addProperty(propId, primitiveValueCache()->createValue(value->string, CSSPrimitiveValue::CSS_STRING), important);
2474         return true;
2475     }
2476     return false;
2477 }
2478 
2479 // <length>{1,2} | auto | [ <page-size> || [ portrait | landscape] ]
parseSize(int propId,bool important)2480 bool CSSParser::parseSize(int propId, bool important)
2481 {
2482     ASSERT(propId == CSSPropertySize);
2483 
2484     if (m_valueList->size() > 2)
2485         return false;
2486 
2487     CSSParserValue* value = m_valueList->current();
2488     if (!value)
2489         return false;
2490 
2491     RefPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated();
2492 
2493     // First parameter.
2494     SizeParameterType paramType = parseSizeParameter(parsedValues.get(), value, None);
2495     if (paramType == None)
2496         return false;
2497 
2498     // Second parameter, if any.
2499     value = m_valueList->next();
2500     if (value) {
2501         paramType = parseSizeParameter(parsedValues.get(), value, paramType);
2502         if (paramType == None)
2503             return false;
2504     }
2505 
2506     addProperty(propId, parsedValues.release(), important);
2507     return true;
2508 }
2509 
parseSizeParameter(CSSValueList * parsedValues,CSSParserValue * value,SizeParameterType prevParamType)2510 CSSParser::SizeParameterType CSSParser::parseSizeParameter(CSSValueList* parsedValues, CSSParserValue* value, SizeParameterType prevParamType)
2511 {
2512     switch (value->id) {
2513     case CSSValueAuto:
2514         if (prevParamType == None) {
2515             parsedValues->append(primitiveValueCache()->createIdentifierValue(value->id));
2516             return Auto;
2517         }
2518         return None;
2519     case CSSValueLandscape:
2520     case CSSValuePortrait:
2521         if (prevParamType == None || prevParamType == PageSize) {
2522             parsedValues->append(primitiveValueCache()->createIdentifierValue(value->id));
2523             return Orientation;
2524         }
2525         return None;
2526     case CSSValueA3:
2527     case CSSValueA4:
2528     case CSSValueA5:
2529     case CSSValueB4:
2530     case CSSValueB5:
2531     case CSSValueLedger:
2532     case CSSValueLegal:
2533     case CSSValueLetter:
2534         if (prevParamType == None || prevParamType == Orientation) {
2535             // Normalize to Page Size then Orientation order by prepending.
2536             // This is not specified by the CSS3 Paged Media specification, but for simpler processing later (CSSStyleSelector::applyPageSizeProperty).
2537             parsedValues->prepend(primitiveValueCache()->createIdentifierValue(value->id));
2538             return PageSize;
2539         }
2540         return None;
2541     case 0:
2542         if (validUnit(value, FLength | FNonNeg, m_strict) && (prevParamType == None || prevParamType == Length)) {
2543             parsedValues->append(primitiveValueCache()->createValue(value->fValue, static_cast<CSSPrimitiveValue::UnitTypes>(value->unit)));
2544             return Length;
2545         }
2546         return None;
2547     default:
2548         return None;
2549     }
2550 }
2551 
2552 // [ <string> <string> ]+ | inherit | none
2553 // inherit and none are handled in parseValue.
parseQuotes(int propId,bool important)2554 bool CSSParser::parseQuotes(int propId, bool important)
2555 {
2556     RefPtr<CSSValueList> values = CSSValueList::createCommaSeparated();
2557     while (CSSParserValue* val = m_valueList->current()) {
2558         RefPtr<CSSValue> parsedValue;
2559         if (val->unit == CSSPrimitiveValue::CSS_STRING)
2560             parsedValue = CSSPrimitiveValue::create(val->string, CSSPrimitiveValue::CSS_STRING);
2561         else
2562             break;
2563         values->append(parsedValue.release());
2564         m_valueList->next();
2565     }
2566     if (values->length()) {
2567         addProperty(propId, values.release(), important);
2568         m_valueList->next();
2569         return true;
2570     }
2571     return false;
2572 }
2573 
2574 // [ <string> | <uri> | <counter> | attr(X) | open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit
2575 // in CSS 2.1 this got somewhat reduced:
2576 // [ <string> | attr(X) | open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit
parseContent(int propId,bool important)2577 bool CSSParser::parseContent(int propId, bool important)
2578 {
2579     RefPtr<CSSValueList> values = CSSValueList::createCommaSeparated();
2580 
2581     while (CSSParserValue* val = m_valueList->current()) {
2582         RefPtr<CSSValue> parsedValue;
2583         if (val->unit == CSSPrimitiveValue::CSS_URI && m_styleSheet) {
2584             // url
2585             // FIXME: The completeURL call should be done when using the CSSImageValue,
2586             // not when creating it.
2587             parsedValue = CSSImageValue::create(m_styleSheet->completeURL(val->string));
2588         } else if (val->unit == CSSParserValue::Function) {
2589             // attr(X) | counter(X [,Y]) | counters(X, Y, [,Z]) | -webkit-gradient(...)
2590             CSSParserValueList* args = val->function->args.get();
2591             if (!args)
2592                 return false;
2593             if (equalIgnoringCase(val->function->name, "attr(")) {
2594                 parsedValue = parseAttr(args);
2595                 if (!parsedValue)
2596                     return false;
2597             } else if (equalIgnoringCase(val->function->name, "counter(")) {
2598                 parsedValue = parseCounterContent(args, false);
2599                 if (!parsedValue)
2600                     return false;
2601             } else if (equalIgnoringCase(val->function->name, "counters(")) {
2602                 parsedValue = parseCounterContent(args, true);
2603                 if (!parsedValue)
2604                     return false;
2605             } else if (isGeneratedImageValue(val)) {
2606                 if (!parseGeneratedImage(parsedValue))
2607                     return false;
2608             } else
2609                 return false;
2610         } else if (val->unit == CSSPrimitiveValue::CSS_IDENT) {
2611             // open-quote
2612             // close-quote
2613             // no-open-quote
2614             // no-close-quote
2615             // inherit
2616             // FIXME: These are not yet implemented (http://bugs.webkit.org/show_bug.cgi?id=6503).
2617             // none
2618             // normal
2619             switch (val->id) {
2620             case CSSValueOpenQuote:
2621             case CSSValueCloseQuote:
2622             case CSSValueNoOpenQuote:
2623             case CSSValueNoCloseQuote:
2624             case CSSValueNone:
2625             case CSSValueNormal:
2626                 parsedValue = primitiveValueCache()->createIdentifierValue(val->id);
2627             }
2628         } else if (val->unit == CSSPrimitiveValue::CSS_STRING) {
2629             parsedValue = primitiveValueCache()->createValue(val->string, CSSPrimitiveValue::CSS_STRING);
2630         }
2631         if (!parsedValue)
2632             break;
2633         values->append(parsedValue.release());
2634         m_valueList->next();
2635     }
2636 
2637     if (values->length()) {
2638         addProperty(propId, values.release(), important);
2639         m_valueList->next();
2640         return true;
2641     }
2642 
2643     return false;
2644 }
2645 
parseAttr(CSSParserValueList * args)2646 PassRefPtr<CSSValue> CSSParser::parseAttr(CSSParserValueList* args)
2647 {
2648     if (args->size() != 1)
2649         return 0;
2650 
2651     CSSParserValue* a = args->current();
2652 
2653     if (a->unit != CSSPrimitiveValue::CSS_IDENT)
2654         return 0;
2655 
2656     String attrName = a->string;
2657     // CSS allows identifiers with "-" at the start, like "-webkit-mask-image".
2658     // But HTML attribute names can't have those characters, and we should not
2659     // even parse them inside attr().
2660     if (attrName[0] == '-')
2661         return 0;
2662 
2663     if (document() && document()->isHTMLDocument())
2664         attrName = attrName.lower();
2665 
2666     return primitiveValueCache()->createValue(attrName, CSSPrimitiveValue::CSS_ATTR);
2667 }
2668 
parseBackgroundColor()2669 PassRefPtr<CSSValue> CSSParser::parseBackgroundColor()
2670 {
2671     int id = m_valueList->current()->id;
2672     if (id == CSSValueWebkitText || (id >= CSSValueAqua && id <= CSSValueWindowtext) || id == CSSValueMenu || id == CSSValueCurrentcolor ||
2673         (id >= CSSValueGrey && id < CSSValueWebkitText && !m_strict))
2674        return primitiveValueCache()->createIdentifierValue(id);
2675     return parseColor();
2676 }
2677 
parseFillImage(RefPtr<CSSValue> & value)2678 bool CSSParser::parseFillImage(RefPtr<CSSValue>& value)
2679 {
2680     if (m_valueList->current()->id == CSSValueNone) {
2681         value = CSSImageValue::create();
2682         return true;
2683     }
2684     if (m_valueList->current()->unit == CSSPrimitiveValue::CSS_URI) {
2685         // FIXME: The completeURL call should be done when using the CSSImageValue,
2686         // not when creating it.
2687         if (m_styleSheet)
2688             value = CSSImageValue::create(m_styleSheet->completeURL(m_valueList->current()->string));
2689         return true;
2690     }
2691 
2692     if (isGeneratedImageValue(m_valueList->current()))
2693         return parseGeneratedImage(value);
2694 
2695     return false;
2696 }
2697 
parseFillPositionX(CSSParserValueList * valueList)2698 PassRefPtr<CSSValue> CSSParser::parseFillPositionX(CSSParserValueList* valueList)
2699 {
2700     int id = valueList->current()->id;
2701     if (id == CSSValueLeft || id == CSSValueRight || id == CSSValueCenter) {
2702         int percent = 0;
2703         if (id == CSSValueRight)
2704             percent = 100;
2705         else if (id == CSSValueCenter)
2706             percent = 50;
2707         return primitiveValueCache()->createValue(percent, CSSPrimitiveValue::CSS_PERCENTAGE);
2708     }
2709     if (validUnit(valueList->current(), FPercent | FLength, m_strict))
2710         return primitiveValueCache()->createValue(valueList->current()->fValue,
2711                                                   (CSSPrimitiveValue::UnitTypes)valueList->current()->unit);
2712     return 0;
2713 }
2714 
parseFillPositionY(CSSParserValueList * valueList)2715 PassRefPtr<CSSValue> CSSParser::parseFillPositionY(CSSParserValueList* valueList)
2716 {
2717     int id = valueList->current()->id;
2718     if (id == CSSValueTop || id == CSSValueBottom || id == CSSValueCenter) {
2719         int percent = 0;
2720         if (id == CSSValueBottom)
2721             percent = 100;
2722         else if (id == CSSValueCenter)
2723             percent = 50;
2724         return primitiveValueCache()->createValue(percent, CSSPrimitiveValue::CSS_PERCENTAGE);
2725     }
2726     if (validUnit(valueList->current(), FPercent | FLength, m_strict))
2727         return primitiveValueCache()->createValue(valueList->current()->fValue,
2728                                                   (CSSPrimitiveValue::UnitTypes)valueList->current()->unit);
2729     return 0;
2730 }
2731 
parseFillPositionComponent(CSSParserValueList * valueList,unsigned & cumulativeFlags,FillPositionFlag & individualFlag)2732 PassRefPtr<CSSValue> CSSParser::parseFillPositionComponent(CSSParserValueList* valueList, unsigned& cumulativeFlags, FillPositionFlag& individualFlag)
2733 {
2734     int id = valueList->current()->id;
2735     if (id == CSSValueLeft || id == CSSValueTop || id == CSSValueRight || id == CSSValueBottom || id == CSSValueCenter) {
2736         int percent = 0;
2737         if (id == CSSValueLeft || id == CSSValueRight) {
2738             if (cumulativeFlags & XFillPosition)
2739                 return 0;
2740             cumulativeFlags |= XFillPosition;
2741             individualFlag = XFillPosition;
2742             if (id == CSSValueRight)
2743                 percent = 100;
2744         }
2745         else if (id == CSSValueTop || id == CSSValueBottom) {
2746             if (cumulativeFlags & YFillPosition)
2747                 return 0;
2748             cumulativeFlags |= YFillPosition;
2749             individualFlag = YFillPosition;
2750             if (id == CSSValueBottom)
2751                 percent = 100;
2752         } else if (id == CSSValueCenter) {
2753             // Center is ambiguous, so we're not sure which position we've found yet, an x or a y.
2754             percent = 50;
2755             cumulativeFlags |= AmbiguousFillPosition;
2756             individualFlag = AmbiguousFillPosition;
2757         }
2758         return primitiveValueCache()->createValue(percent, CSSPrimitiveValue::CSS_PERCENTAGE);
2759     }
2760     if (validUnit(valueList->current(), FPercent | FLength, m_strict)) {
2761         if (!cumulativeFlags) {
2762             cumulativeFlags |= XFillPosition;
2763             individualFlag = XFillPosition;
2764         } else if (cumulativeFlags & (XFillPosition | AmbiguousFillPosition)) {
2765             cumulativeFlags |= YFillPosition;
2766             individualFlag = YFillPosition;
2767         } else
2768             return 0;
2769         return primitiveValueCache()->createValue(valueList->current()->fValue,
2770                                                   (CSSPrimitiveValue::UnitTypes)valueList->current()->unit);
2771     }
2772     return 0;
2773 }
2774 
parseFillPosition(CSSParserValueList * valueList,RefPtr<CSSValue> & value1,RefPtr<CSSValue> & value2)2775 void CSSParser::parseFillPosition(CSSParserValueList* valueList, RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2)
2776 {
2777     CSSParserValue* value = valueList->current();
2778 
2779     // Parse the first value.  We're just making sure that it is one of the valid keywords or a percentage/length.
2780     unsigned cumulativeFlags = 0;
2781     FillPositionFlag value1Flag = InvalidFillPosition;
2782     FillPositionFlag value2Flag = InvalidFillPosition;
2783     value1 = parseFillPositionComponent(valueList, cumulativeFlags, value1Flag);
2784     if (!value1)
2785         return;
2786 
2787     // It only takes one value for background-position to be correctly parsed if it was specified in a shorthand (since we
2788     // can assume that any other values belong to the rest of the shorthand).  If we're not parsing a shorthand, though, the
2789     // value was explicitly specified for our property.
2790     value = valueList->next();
2791 
2792     // First check for the comma.  If so, we are finished parsing this value or value pair.
2793     if (value && value->unit == CSSParserValue::Operator && value->iValue == ',')
2794         value = 0;
2795 
2796     if (value) {
2797         value2 = parseFillPositionComponent(valueList, cumulativeFlags, value2Flag);
2798         if (value2)
2799             valueList->next();
2800         else {
2801             if (!inShorthand()) {
2802                 value1.clear();
2803                 return;
2804             }
2805         }
2806     }
2807 
2808     if (!value2)
2809         // Only one value was specified.  If that value was not a keyword, then it sets the x position, and the y position
2810         // is simply 50%.  This is our default.
2811         // For keywords, the keyword was either an x-keyword (left/right), a y-keyword (top/bottom), or an ambiguous keyword (center).
2812         // For left/right/center, the default of 50% in the y is still correct.
2813         value2 = primitiveValueCache()->createValue(50, CSSPrimitiveValue::CSS_PERCENTAGE);
2814 
2815     if (value1Flag == YFillPosition || value2Flag == XFillPosition)
2816         value1.swap(value2);
2817 }
2818 
parseFillRepeat(RefPtr<CSSValue> & value1,RefPtr<CSSValue> & value2)2819 void CSSParser::parseFillRepeat(RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2)
2820 {
2821     CSSParserValue* value = m_valueList->current();
2822 
2823     int id = m_valueList->current()->id;
2824     if (id == CSSValueRepeatX) {
2825         m_implicitShorthand = true;
2826         value1 = primitiveValueCache()->createIdentifierValue(CSSValueRepeat);
2827         value2 = primitiveValueCache()->createIdentifierValue(CSSValueNoRepeat);
2828         m_valueList->next();
2829         return;
2830     }
2831     if (id == CSSValueRepeatY) {
2832         m_implicitShorthand = true;
2833         value1 = primitiveValueCache()->createIdentifierValue(CSSValueNoRepeat);
2834         value2 = primitiveValueCache()->createIdentifierValue(CSSValueRepeat);
2835         m_valueList->next();
2836         return;
2837     }
2838     if (id == CSSValueRepeat || id == CSSValueNoRepeat || id == CSSValueRound || id == CSSValueSpace)
2839         value1 = primitiveValueCache()->createIdentifierValue(id);
2840     else {
2841         value1 = 0;
2842         return;
2843     }
2844 
2845     value = m_valueList->next();
2846 
2847     // First check for the comma.  If so, we are finished parsing this value or value pair.
2848     if (value && value->unit == CSSParserValue::Operator && value->iValue == ',')
2849         value = 0;
2850 
2851     if (value)
2852         id = m_valueList->current()->id;
2853 
2854     if (value && (id == CSSValueRepeat || id == CSSValueNoRepeat || id == CSSValueRound || id == CSSValueSpace)) {
2855         value2 = primitiveValueCache()->createIdentifierValue(id);
2856         m_valueList->next();
2857     } else {
2858         // If only one value was specified, value2 is the same as value1.
2859         m_implicitShorthand = true;
2860         value2 = primitiveValueCache()->createIdentifierValue(static_cast<CSSPrimitiveValue*>(value1.get())->getIdent());
2861     }
2862 }
2863 
parseFillSize(int propId,bool & allowComma)2864 PassRefPtr<CSSValue> CSSParser::parseFillSize(int propId, bool& allowComma)
2865 {
2866     allowComma = true;
2867     CSSParserValue* value = m_valueList->current();
2868 
2869     if (value->id == CSSValueContain || value->id == CSSValueCover)
2870         return primitiveValueCache()->createIdentifierValue(value->id);
2871 
2872     RefPtr<CSSPrimitiveValue> parsedValue1;
2873 
2874     if (value->id == CSSValueAuto)
2875         parsedValue1 = primitiveValueCache()->createValue(0, CSSPrimitiveValue::CSS_UNKNOWN);
2876     else {
2877         if (!validUnit(value, FLength | FPercent, m_strict))
2878             return 0;
2879         parsedValue1 = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit);
2880     }
2881 
2882     CSSPropertyID property = static_cast<CSSPropertyID>(propId);
2883     RefPtr<CSSPrimitiveValue> parsedValue2;
2884     if ((value = m_valueList->next())) {
2885         if (value->id == CSSValueAuto)
2886             parsedValue2 = primitiveValueCache()->createValue(0, CSSPrimitiveValue::CSS_UNKNOWN);
2887         else if (value->unit == CSSParserValue::Operator && value->iValue == ',')
2888             allowComma = false;
2889         else {
2890             if (!validUnit(value, FLength | FPercent, m_strict))
2891                 return 0;
2892             parsedValue2 = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit);
2893         }
2894     }
2895     if (!parsedValue2) {
2896         if (property == CSSPropertyWebkitBackgroundSize || property == CSSPropertyWebkitMaskSize)
2897             parsedValue2 = parsedValue1;
2898         else
2899             parsedValue2 = primitiveValueCache()->createValue(0, CSSPrimitiveValue::CSS_UNKNOWN);
2900     }
2901 
2902     return primitiveValueCache()->createValue(Pair::create(parsedValue1.release(), parsedValue2.release()));
2903 }
2904 
parseFillProperty(int propId,int & propId1,int & propId2,RefPtr<CSSValue> & retValue1,RefPtr<CSSValue> & retValue2)2905 bool CSSParser::parseFillProperty(int propId, int& propId1, int& propId2,
2906                                   RefPtr<CSSValue>& retValue1, RefPtr<CSSValue>& retValue2)
2907 {
2908     RefPtr<CSSValueList> values;
2909     RefPtr<CSSValueList> values2;
2910     CSSParserValue* val;
2911     RefPtr<CSSValue> value;
2912     RefPtr<CSSValue> value2;
2913 
2914     bool allowComma = false;
2915 
2916     retValue1 = retValue2 = 0;
2917     propId1 = propId;
2918     propId2 = propId;
2919     if (propId == CSSPropertyBackgroundPosition) {
2920         propId1 = CSSPropertyBackgroundPositionX;
2921         propId2 = CSSPropertyBackgroundPositionY;
2922     } else if (propId == CSSPropertyWebkitMaskPosition) {
2923         propId1 = CSSPropertyWebkitMaskPositionX;
2924         propId2 = CSSPropertyWebkitMaskPositionY;
2925     } else if (propId == CSSPropertyBackgroundRepeat) {
2926         propId1 = CSSPropertyBackgroundRepeatX;
2927         propId2 = CSSPropertyBackgroundRepeatY;
2928     } else if (propId == CSSPropertyWebkitMaskRepeat) {
2929         propId1 = CSSPropertyWebkitMaskRepeatX;
2930         propId2 = CSSPropertyWebkitMaskRepeatY;
2931     }
2932 
2933     while ((val = m_valueList->current())) {
2934         RefPtr<CSSValue> currValue;
2935         RefPtr<CSSValue> currValue2;
2936 
2937         if (allowComma) {
2938             if (val->unit != CSSParserValue::Operator || val->iValue != ',')
2939                 return false;
2940             m_valueList->next();
2941             allowComma = false;
2942         } else {
2943             allowComma = true;
2944             switch (propId) {
2945                 case CSSPropertyBackgroundColor:
2946                     currValue = parseBackgroundColor();
2947                     if (currValue)
2948                         m_valueList->next();
2949                     break;
2950                 case CSSPropertyBackgroundAttachment:
2951                 case CSSPropertyWebkitMaskAttachment:
2952                     if (val->id == CSSValueScroll || val->id == CSSValueFixed || val->id == CSSValueLocal) {
2953                         currValue = primitiveValueCache()->createIdentifierValue(val->id);
2954                         m_valueList->next();
2955                     }
2956                     break;
2957                 case CSSPropertyBackgroundImage:
2958                 case CSSPropertyWebkitMaskImage:
2959                     if (parseFillImage(currValue))
2960                         m_valueList->next();
2961                     break;
2962                 case CSSPropertyWebkitBackgroundClip:
2963                 case CSSPropertyWebkitBackgroundOrigin:
2964                 case CSSPropertyWebkitMaskClip:
2965                 case CSSPropertyWebkitMaskOrigin:
2966                     // The first three values here are deprecated and do not apply to the version of the property that has
2967                     // the -webkit- prefix removed.
2968                     if (val->id == CSSValueBorder || val->id == CSSValuePadding || val->id == CSSValueContent ||
2969                         val->id == CSSValueBorderBox || val->id == CSSValuePaddingBox || val->id == CSSValueContentBox ||
2970                         ((propId == CSSPropertyWebkitBackgroundClip || propId == CSSPropertyWebkitMaskClip) &&
2971                          (val->id == CSSValueText || val->id == CSSValueWebkitText))) {
2972                         currValue = primitiveValueCache()->createIdentifierValue(val->id);
2973                         m_valueList->next();
2974                     }
2975                     break;
2976                 case CSSPropertyBackgroundClip:
2977                     if (parseBackgroundClip(val, currValue, primitiveValueCache()))
2978                         m_valueList->next();
2979                     break;
2980                 case CSSPropertyBackgroundOrigin:
2981                     if (val->id == CSSValueBorderBox || val->id == CSSValuePaddingBox || val->id == CSSValueContentBox) {
2982                         currValue = primitiveValueCache()->createIdentifierValue(val->id);
2983                         m_valueList->next();
2984                     }
2985                     break;
2986                 case CSSPropertyBackgroundPosition:
2987                 case CSSPropertyWebkitMaskPosition:
2988                     parseFillPosition(m_valueList, currValue, currValue2);
2989                     // parseFillPosition advances the m_valueList pointer
2990                     break;
2991                 case CSSPropertyBackgroundPositionX:
2992                 case CSSPropertyWebkitMaskPositionX: {
2993                     currValue = parseFillPositionX(m_valueList);
2994                     if (currValue)
2995                         m_valueList->next();
2996                     break;
2997                 }
2998                 case CSSPropertyBackgroundPositionY:
2999                 case CSSPropertyWebkitMaskPositionY: {
3000                     currValue = parseFillPositionY(m_valueList);
3001                     if (currValue)
3002                         m_valueList->next();
3003                     break;
3004                 }
3005                 case CSSPropertyWebkitBackgroundComposite:
3006                 case CSSPropertyWebkitMaskComposite:
3007                     if ((val->id >= CSSValueClear && val->id <= CSSValuePlusLighter) || val->id == CSSValueHighlight) {
3008                         currValue = primitiveValueCache()->createIdentifierValue(val->id);
3009                         m_valueList->next();
3010                     }
3011                     break;
3012                 case CSSPropertyBackgroundRepeat:
3013                 case CSSPropertyWebkitMaskRepeat:
3014                     parseFillRepeat(currValue, currValue2);
3015                     // parseFillRepeat advances the m_valueList pointer
3016                     break;
3017                 case CSSPropertyBackgroundSize:
3018                 case CSSPropertyWebkitBackgroundSize:
3019                 case CSSPropertyWebkitMaskSize: {
3020                     currValue = parseFillSize(propId, allowComma);
3021                     if (currValue)
3022                         m_valueList->next();
3023                     break;
3024                 }
3025             }
3026             if (!currValue)
3027                 return false;
3028 
3029             if (value && !values) {
3030                 values = CSSValueList::createCommaSeparated();
3031                 values->append(value.release());
3032             }
3033 
3034             if (value2 && !values2) {
3035                 values2 = CSSValueList::createCommaSeparated();
3036                 values2->append(value2.release());
3037             }
3038 
3039             if (values)
3040                 values->append(currValue.release());
3041             else
3042                 value = currValue.release();
3043             if (currValue2) {
3044                 if (values2)
3045                     values2->append(currValue2.release());
3046                 else
3047                     value2 = currValue2.release();
3048             }
3049         }
3050 
3051         // When parsing any fill shorthand property, we let it handle building up the lists for all
3052         // properties.
3053         if (inShorthand())
3054             break;
3055     }
3056 
3057     if (values && values->length()) {
3058         retValue1 = values.release();
3059         if (values2 && values2->length())
3060             retValue2 = values2.release();
3061         return true;
3062     }
3063     if (value) {
3064         retValue1 = value.release();
3065         retValue2 = value2.release();
3066         return true;
3067     }
3068     return false;
3069 }
3070 
parseAnimationDelay()3071 PassRefPtr<CSSValue> CSSParser::parseAnimationDelay()
3072 {
3073     CSSParserValue* value = m_valueList->current();
3074     if (validUnit(value, FTime, m_strict))
3075         return primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit);
3076     return 0;
3077 }
3078 
parseAnimationDirection()3079 PassRefPtr<CSSValue> CSSParser::parseAnimationDirection()
3080 {
3081     CSSParserValue* value = m_valueList->current();
3082     if (value->id == CSSValueNormal || value->id == CSSValueAlternate)
3083         return primitiveValueCache()->createIdentifierValue(value->id);
3084     return 0;
3085 }
3086 
parseAnimationDuration()3087 PassRefPtr<CSSValue> CSSParser::parseAnimationDuration()
3088 {
3089     CSSParserValue* value = m_valueList->current();
3090     if (validUnit(value, FTime | FNonNeg, m_strict))
3091         return primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit);
3092     return 0;
3093 }
3094 
parseAnimationFillMode()3095 PassRefPtr<CSSValue> CSSParser::parseAnimationFillMode()
3096 {
3097     CSSParserValue* value = m_valueList->current();
3098     if (value->id == CSSValueNone || value->id == CSSValueForwards || value->id == CSSValueBackwards || value->id == CSSValueBoth)
3099         return primitiveValueCache()->createIdentifierValue(value->id);
3100     return 0;
3101 }
3102 
parseAnimationIterationCount()3103 PassRefPtr<CSSValue> CSSParser::parseAnimationIterationCount()
3104 {
3105     CSSParserValue* value = m_valueList->current();
3106     if (value->id == CSSValueInfinite)
3107         return primitiveValueCache()->createIdentifierValue(value->id);
3108     if (validUnit(value, FInteger | FNonNeg, m_strict))
3109         return primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes)value->unit);
3110     return 0;
3111 }
3112 
parseAnimationName()3113 PassRefPtr<CSSValue> CSSParser::parseAnimationName()
3114 {
3115     CSSParserValue* value = m_valueList->current();
3116     if (value->unit == CSSPrimitiveValue::CSS_STRING || value->unit == CSSPrimitiveValue::CSS_IDENT) {
3117         if (value->id == CSSValueNone || (value->unit == CSSPrimitiveValue::CSS_STRING && equalIgnoringCase(value->string, "none"))) {
3118             return primitiveValueCache()->createIdentifierValue(CSSValueNone);
3119         } else {
3120             return primitiveValueCache()->createValue(value->string, CSSPrimitiveValue::CSS_STRING);
3121         }
3122     }
3123     return 0;
3124 }
3125 
parseAnimationPlayState()3126 PassRefPtr<CSSValue> CSSParser::parseAnimationPlayState()
3127 {
3128     CSSParserValue* value = m_valueList->current();
3129     if (value->id == CSSValueRunning || value->id == CSSValuePaused)
3130         return primitiveValueCache()->createIdentifierValue(value->id);
3131     return 0;
3132 }
3133 
parseAnimationProperty()3134 PassRefPtr<CSSValue> CSSParser::parseAnimationProperty()
3135 {
3136     CSSParserValue* value = m_valueList->current();
3137     if (value->unit != CSSPrimitiveValue::CSS_IDENT)
3138         return 0;
3139     int result = cssPropertyID(value->string);
3140     if (result)
3141         return primitiveValueCache()->createIdentifierValue(result);
3142     if (equalIgnoringCase(value->string, "all"))
3143         return primitiveValueCache()->createIdentifierValue(CSSValueAll);
3144     if (equalIgnoringCase(value->string, "none"))
3145         return primitiveValueCache()->createIdentifierValue(CSSValueNone);
3146     return 0;
3147 }
3148 
parseTransformOriginShorthand(RefPtr<CSSValue> & value1,RefPtr<CSSValue> & value2,RefPtr<CSSValue> & value3)3149 bool CSSParser::parseTransformOriginShorthand(RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2, RefPtr<CSSValue>& value3)
3150 {
3151     parseFillPosition(m_valueList, value1, value2);
3152 
3153     // now get z
3154     if (m_valueList->current()) {
3155         if (validUnit(m_valueList->current(), FLength, m_strict)) {
3156             value3 = primitiveValueCache()->createValue(m_valueList->current()->fValue,
3157                                              (CSSPrimitiveValue::UnitTypes)m_valueList->current()->unit);
3158             m_valueList->next();
3159             return true;
3160         }
3161         return false;
3162     }
3163     return true;
3164 }
3165 
parseCubicBezierTimingFunctionValue(CSSParserValueList * & args,double & result)3166 bool CSSParser::parseCubicBezierTimingFunctionValue(CSSParserValueList*& args, double& result)
3167 {
3168     CSSParserValue* v = args->current();
3169     if (!validUnit(v, FNumber, m_strict))
3170         return false;
3171     result = v->fValue;
3172     if (result < 0 || result > 1.0)
3173         return false;
3174     v = args->next();
3175     if (!v)
3176         // The last number in the function has no comma after it, so we're done.
3177         return true;
3178     if (v->unit != CSSParserValue::Operator && v->iValue != ',')
3179         return false;
3180     v = args->next();
3181     return true;
3182 }
3183 
parseAnimationTimingFunction()3184 PassRefPtr<CSSValue> CSSParser::parseAnimationTimingFunction()
3185 {
3186     CSSParserValue* value = m_valueList->current();
3187     if (value->id == CSSValueEase || value->id == CSSValueLinear || value->id == CSSValueEaseIn || value->id == CSSValueEaseOut
3188         || value->id == CSSValueEaseInOut || value->id == CSSValueStepStart || value->id == CSSValueStepEnd)
3189         return primitiveValueCache()->createIdentifierValue(value->id);
3190 
3191     // We must be a function.
3192     if (value->unit != CSSParserValue::Function)
3193         return 0;
3194 
3195     CSSParserValueList* args = value->function->args.get();
3196 
3197     if (equalIgnoringCase(value->function->name, "steps(")) {
3198         // For steps, 1 or 2 params must be specified (comma-separated)
3199         if (!args || (args->size() != 1 && args->size() != 3))
3200             return 0;
3201 
3202         // There are two values.
3203         int numSteps;
3204         bool stepAtStart = false;
3205 
3206         CSSParserValue* v = args->current();
3207         if (!validUnit(v, FInteger, m_strict))
3208             return 0;
3209         numSteps = (int) min(v->fValue, (double)INT_MAX);
3210         if (numSteps < 1)
3211             return 0;
3212         v = args->next();
3213 
3214         if (v) {
3215             // There is a comma so we need to parse the second value
3216             if (v->unit != CSSParserValue::Operator && v->iValue != ',')
3217                 return 0;
3218             v = args->next();
3219             if (v->id != CSSValueStart && v->id != CSSValueEnd)
3220                 return 0;
3221             stepAtStart = v->id == CSSValueStart;
3222         }
3223 
3224         return CSSStepsTimingFunctionValue::create(numSteps, stepAtStart);
3225     }
3226 
3227     if (equalIgnoringCase(value->function->name, "cubic-bezier(")) {
3228         // For cubic bezier, 4 values must be specified.
3229         if (!args || args->size() != 7)
3230             return 0;
3231 
3232         // There are two points specified.  The values must be between 0 and 1.
3233         double x1, y1, x2, y2;
3234 
3235         if (!parseCubicBezierTimingFunctionValue(args, x1))
3236             return 0;
3237         if (!parseCubicBezierTimingFunctionValue(args, y1))
3238             return 0;
3239         if (!parseCubicBezierTimingFunctionValue(args, x2))
3240             return 0;
3241         if (!parseCubicBezierTimingFunctionValue(args, y2))
3242             return 0;
3243 
3244         return CSSCubicBezierTimingFunctionValue::create(x1, y1, x2, y2);
3245     }
3246 
3247     return 0;
3248 }
3249 
parseAnimationProperty(int propId,RefPtr<CSSValue> & result)3250 bool CSSParser::parseAnimationProperty(int propId, RefPtr<CSSValue>& result)
3251 {
3252     RefPtr<CSSValueList> values;
3253     CSSParserValue* val;
3254     RefPtr<CSSValue> value;
3255     bool allowComma = false;
3256 
3257     result = 0;
3258 
3259     while ((val = m_valueList->current())) {
3260         RefPtr<CSSValue> currValue;
3261         if (allowComma) {
3262             if (val->unit != CSSParserValue::Operator || val->iValue != ',')
3263                 return false;
3264             m_valueList->next();
3265             allowComma = false;
3266         }
3267         else {
3268             switch (propId) {
3269                 case CSSPropertyWebkitAnimationDelay:
3270                 case CSSPropertyWebkitTransitionDelay:
3271                     currValue = parseAnimationDelay();
3272                     if (currValue)
3273                         m_valueList->next();
3274                     break;
3275                 case CSSPropertyWebkitAnimationDirection:
3276                     currValue = parseAnimationDirection();
3277                     if (currValue)
3278                         m_valueList->next();
3279                     break;
3280                 case CSSPropertyWebkitAnimationDuration:
3281                 case CSSPropertyWebkitTransitionDuration:
3282                     currValue = parseAnimationDuration();
3283                     if (currValue)
3284                         m_valueList->next();
3285                     break;
3286                 case CSSPropertyWebkitAnimationFillMode:
3287                     currValue = parseAnimationFillMode();
3288                     if (currValue)
3289                         m_valueList->next();
3290                     break;
3291                 case CSSPropertyWebkitAnimationIterationCount:
3292                     currValue = parseAnimationIterationCount();
3293                     if (currValue)
3294                         m_valueList->next();
3295                     break;
3296                 case CSSPropertyWebkitAnimationName:
3297                     currValue = parseAnimationName();
3298                     if (currValue)
3299                         m_valueList->next();
3300                     break;
3301                 case CSSPropertyWebkitAnimationPlayState:
3302                     currValue = parseAnimationPlayState();
3303                     if (currValue)
3304                         m_valueList->next();
3305                     break;
3306                 case CSSPropertyWebkitTransitionProperty:
3307                     currValue = parseAnimationProperty();
3308                     if (currValue)
3309                         m_valueList->next();
3310                     break;
3311                 case CSSPropertyWebkitAnimationTimingFunction:
3312                 case CSSPropertyWebkitTransitionTimingFunction:
3313                     currValue = parseAnimationTimingFunction();
3314                     if (currValue)
3315                         m_valueList->next();
3316                     break;
3317             }
3318 
3319             if (!currValue)
3320                 return false;
3321 
3322             if (value && !values) {
3323                 values = CSSValueList::createCommaSeparated();
3324                 values->append(value.release());
3325             }
3326 
3327             if (values)
3328                 values->append(currValue.release());
3329             else
3330                 value = currValue.release();
3331 
3332             allowComma = true;
3333         }
3334 
3335         // When parsing the 'transition' shorthand property, we let it handle building up the lists for all
3336         // properties.
3337         if (inShorthand())
3338             break;
3339     }
3340 
3341     if (values && values->length()) {
3342         result = values.release();
3343         return true;
3344     }
3345     if (value) {
3346         result = value.release();
3347         return true;
3348     }
3349     return false;
3350 }
3351 
3352 
3353 
3354 #if ENABLE(DASHBOARD_SUPPORT)
3355 
3356 #define DASHBOARD_REGION_NUM_PARAMETERS  6
3357 #define DASHBOARD_REGION_SHORT_NUM_PARAMETERS  2
3358 
skipCommaInDashboardRegion(CSSParserValueList * args)3359 static CSSParserValue* skipCommaInDashboardRegion(CSSParserValueList *args)
3360 {
3361     if (args->size() == (DASHBOARD_REGION_NUM_PARAMETERS*2-1) ||
3362          args->size() == (DASHBOARD_REGION_SHORT_NUM_PARAMETERS*2-1)) {
3363         CSSParserValue* current = args->current();
3364         if (current->unit == CSSParserValue::Operator && current->iValue == ',')
3365             return args->next();
3366     }
3367     return args->current();
3368 }
3369 
parseDashboardRegions(int propId,bool important)3370 bool CSSParser::parseDashboardRegions(int propId, bool important)
3371 {
3372     bool valid = true;
3373 
3374     CSSParserValue* value = m_valueList->current();
3375 
3376     if (value->id == CSSValueNone) {
3377         if (m_valueList->next())
3378             return false;
3379         addProperty(propId, primitiveValueCache()->createIdentifierValue(value->id), important);
3380         return valid;
3381     }
3382 
3383     RefPtr<DashboardRegion> firstRegion = DashboardRegion::create();
3384     DashboardRegion* region = 0;
3385 
3386     while (value) {
3387         if (region == 0) {
3388             region = firstRegion.get();
3389         } else {
3390             RefPtr<DashboardRegion> nextRegion = DashboardRegion::create();
3391             region->m_next = nextRegion;
3392             region = nextRegion.get();
3393         }
3394 
3395         if (value->unit != CSSParserValue::Function) {
3396             valid = false;
3397             break;
3398         }
3399 
3400         // Commas count as values, so allow:
3401         // dashboard-region(label, type, t, r, b, l) or dashboard-region(label type t r b l)
3402         // dashboard-region(label, type, t, r, b, l) or dashboard-region(label type t r b l)
3403         // also allow
3404         // dashboard-region(label, type) or dashboard-region(label type)
3405         // dashboard-region(label, type) or dashboard-region(label type)
3406         CSSParserValueList* args = value->function->args.get();
3407         if (!equalIgnoringCase(value->function->name, "dashboard-region(") || !args) {
3408             valid = false;
3409             break;
3410         }
3411 
3412         int numArgs = args->size();
3413         if ((numArgs != DASHBOARD_REGION_NUM_PARAMETERS && numArgs != (DASHBOARD_REGION_NUM_PARAMETERS*2-1)) &&
3414             (numArgs != DASHBOARD_REGION_SHORT_NUM_PARAMETERS && numArgs != (DASHBOARD_REGION_SHORT_NUM_PARAMETERS*2-1))) {
3415             valid = false;
3416             break;
3417         }
3418 
3419         // First arg is a label.
3420         CSSParserValue* arg = args->current();
3421         if (arg->unit != CSSPrimitiveValue::CSS_IDENT) {
3422             valid = false;
3423             break;
3424         }
3425 
3426         region->m_label = arg->string;
3427 
3428         // Second arg is a type.
3429         arg = args->next();
3430         arg = skipCommaInDashboardRegion(args);
3431         if (arg->unit != CSSPrimitiveValue::CSS_IDENT) {
3432             valid = false;
3433             break;
3434         }
3435 
3436         if (equalIgnoringCase(arg->string, "circle"))
3437             region->m_isCircle = true;
3438         else if (equalIgnoringCase(arg->string, "rectangle"))
3439             region->m_isRectangle = true;
3440         else {
3441             valid = false;
3442             break;
3443         }
3444 
3445         region->m_geometryType = arg->string;
3446 
3447         if (numArgs == DASHBOARD_REGION_SHORT_NUM_PARAMETERS || numArgs == (DASHBOARD_REGION_SHORT_NUM_PARAMETERS*2-1)) {
3448             // This originally used CSSValueInvalid by accident. It might be more logical to use something else.
3449             RefPtr<CSSPrimitiveValue> amount = primitiveValueCache()->createIdentifierValue(CSSValueInvalid);
3450 
3451             region->setTop(amount);
3452             region->setRight(amount);
3453             region->setBottom(amount);
3454             region->setLeft(amount);
3455         } else {
3456             // Next four arguments must be offset numbers
3457             int i;
3458             for (i = 0; i < 4; i++) {
3459                 arg = args->next();
3460                 arg = skipCommaInDashboardRegion(args);
3461 
3462                 valid = arg->id == CSSValueAuto || validUnit(arg, FLength, m_strict);
3463                 if (!valid)
3464                     break;
3465 
3466                 RefPtr<CSSPrimitiveValue> amount = arg->id == CSSValueAuto ?
3467                     primitiveValueCache()->createIdentifierValue(CSSValueAuto) :
3468                     primitiveValueCache()->createValue(arg->fValue, (CSSPrimitiveValue::UnitTypes) arg->unit);
3469 
3470                 if (i == 0)
3471                     region->setTop(amount);
3472                 else if (i == 1)
3473                     region->setRight(amount);
3474                 else if (i == 2)
3475                     region->setBottom(amount);
3476                 else
3477                     region->setLeft(amount);
3478             }
3479         }
3480 
3481         if (args->next())
3482             return false;
3483 
3484         value = m_valueList->next();
3485     }
3486 
3487     if (valid)
3488         addProperty(propId, primitiveValueCache()->createValue(firstRegion.release()), important);
3489 
3490     return valid;
3491 }
3492 
3493 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3494 
parseCounterContent(CSSParserValueList * args,bool counters)3495 PassRefPtr<CSSValue> CSSParser::parseCounterContent(CSSParserValueList* args, bool counters)
3496 {
3497     unsigned numArgs = args->size();
3498     if (counters && numArgs != 3 && numArgs != 5)
3499         return 0;
3500     if (!counters && numArgs != 1 && numArgs != 3)
3501         return 0;
3502 
3503     CSSParserValue* i = args->current();
3504     if (i->unit != CSSPrimitiveValue::CSS_IDENT)
3505         return 0;
3506     RefPtr<CSSPrimitiveValue> identifier = primitiveValueCache()->createValue(i->string, CSSPrimitiveValue::CSS_STRING);
3507 
3508     RefPtr<CSSPrimitiveValue> separator;
3509     if (!counters)
3510         separator = primitiveValueCache()->createValue(String(), CSSPrimitiveValue::CSS_STRING);
3511     else {
3512         i = args->next();
3513         if (i->unit != CSSParserValue::Operator || i->iValue != ',')
3514             return 0;
3515 
3516         i = args->next();
3517         if (i->unit != CSSPrimitiveValue::CSS_STRING)
3518             return 0;
3519 
3520         separator = primitiveValueCache()->createValue(i->string, (CSSPrimitiveValue::UnitTypes) i->unit);
3521     }
3522 
3523     RefPtr<CSSPrimitiveValue> listStyle;
3524     i = args->next();
3525     if (!i) // Make the list style default decimal
3526         listStyle = primitiveValueCache()->createValue(CSSValueDecimal - CSSValueDisc, CSSPrimitiveValue::CSS_NUMBER);
3527     else {
3528         if (i->unit != CSSParserValue::Operator || i->iValue != ',')
3529             return 0;
3530 
3531         i = args->next();
3532         if (i->unit != CSSPrimitiveValue::CSS_IDENT)
3533             return 0;
3534 
3535         short ls = 0;
3536         if (i->id == CSSValueNone)
3537             ls = CSSValueKatakanaIroha - CSSValueDisc + 1;
3538         else if (i->id >= CSSValueDisc && i->id <= CSSValueKatakanaIroha)
3539             ls = i->id - CSSValueDisc;
3540         else
3541             return 0;
3542 
3543         listStyle = primitiveValueCache()->createValue(ls, (CSSPrimitiveValue::UnitTypes) i->unit);
3544     }
3545 
3546     return primitiveValueCache()->createValue(Counter::create(identifier.release(), listStyle.release(), separator.release()));
3547 }
3548 
parseShape(int propId,bool important)3549 bool CSSParser::parseShape(int propId, bool important)
3550 {
3551     CSSParserValue* value = m_valueList->current();
3552     CSSParserValueList* args = value->function->args.get();
3553 
3554     if (!equalIgnoringCase(value->function->name, "rect(") || !args)
3555         return false;
3556 
3557     // rect(t, r, b, l) || rect(t r b l)
3558     if (args->size() != 4 && args->size() != 7)
3559         return false;
3560     RefPtr<Rect> rect = Rect::create();
3561     bool valid = true;
3562     int i = 0;
3563     CSSParserValue* a = args->current();
3564     while (a) {
3565         valid = a->id == CSSValueAuto || validUnit(a, FLength, m_strict);
3566         if (!valid)
3567             break;
3568         RefPtr<CSSPrimitiveValue> length = a->id == CSSValueAuto ?
3569             primitiveValueCache()->createIdentifierValue(CSSValueAuto) :
3570             primitiveValueCache()->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes) a->unit);
3571         if (i == 0)
3572             rect->setTop(length);
3573         else if (i == 1)
3574             rect->setRight(length);
3575         else if (i == 2)
3576             rect->setBottom(length);
3577         else
3578             rect->setLeft(length);
3579         a = args->next();
3580         if (a && args->size() == 7) {
3581             if (a->unit == CSSParserValue::Operator && a->iValue == ',') {
3582                 a = args->next();
3583             } else {
3584                 valid = false;
3585                 break;
3586             }
3587         }
3588         i++;
3589     }
3590     if (valid) {
3591         addProperty(propId, primitiveValueCache()->createValue(rect.release()), important);
3592         m_valueList->next();
3593         return true;
3594     }
3595     return false;
3596 }
3597 
3598 // [ 'font-style' || 'font-variant' || 'font-weight' ]? 'font-size' [ / 'line-height' ]? 'font-family'
parseFont(bool important)3599 bool CSSParser::parseFont(bool important)
3600 {
3601     bool valid = true;
3602     CSSParserValue *value = m_valueList->current();
3603     RefPtr<FontValue> font = FontValue::create();
3604     // optional font-style, font-variant and font-weight
3605     while (value) {
3606         int id = value->id;
3607         if (id) {
3608             if (id == CSSValueNormal) {
3609                 // do nothing, it's the inital value for all three
3610             } else if (id == CSSValueItalic || id == CSSValueOblique) {
3611                 if (font->style)
3612                     return false;
3613                 font->style = primitiveValueCache()->createIdentifierValue(id);
3614             } else if (id == CSSValueSmallCaps) {
3615                 if (font->variant)
3616                     return false;
3617                 font->variant = primitiveValueCache()->createIdentifierValue(id);
3618             } else if (id >= CSSValueBold && id <= CSSValueLighter) {
3619                 if (font->weight)
3620                     return false;
3621                 font->weight = primitiveValueCache()->createIdentifierValue(id);
3622             } else {
3623                 valid = false;
3624             }
3625         } else if (!font->weight && validUnit(value, FInteger | FNonNeg, true)) {
3626             int weight = (int)value->fValue;
3627             int val = 0;
3628             if (weight == 100)
3629                 val = CSSValue100;
3630             else if (weight == 200)
3631                 val = CSSValue200;
3632             else if (weight == 300)
3633                 val = CSSValue300;
3634             else if (weight == 400)
3635                 val = CSSValue400;
3636             else if (weight == 500)
3637                 val = CSSValue500;
3638             else if (weight == 600)
3639                 val = CSSValue600;
3640             else if (weight == 700)
3641                 val = CSSValue700;
3642             else if (weight == 800)
3643                 val = CSSValue800;
3644             else if (weight == 900)
3645                 val = CSSValue900;
3646 
3647             if (val)
3648                 font->weight = primitiveValueCache()->createIdentifierValue(val);
3649             else
3650                 valid = false;
3651         } else {
3652             valid = false;
3653         }
3654         if (!valid)
3655             break;
3656         value = m_valueList->next();
3657     }
3658     if (!value)
3659         return false;
3660 
3661     // set undefined values to default
3662     if (!font->style)
3663         font->style = primitiveValueCache()->createIdentifierValue(CSSValueNormal);
3664     if (!font->variant)
3665         font->variant = primitiveValueCache()->createIdentifierValue(CSSValueNormal);
3666     if (!font->weight)
3667         font->weight = primitiveValueCache()->createIdentifierValue(CSSValueNormal);
3668 
3669     // now a font size _must_ come
3670     // <absolute-size> | <relative-size> | <length> | <percentage> | inherit
3671     if (value->id >= CSSValueXxSmall && value->id <= CSSValueLarger)
3672         font->size = primitiveValueCache()->createIdentifierValue(value->id);
3673     else if (validUnit(value, FLength | FPercent | FNonNeg, m_strict))
3674         font->size = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes) value->unit);
3675     value = m_valueList->next();
3676     if (!font->size || !value)
3677         return false;
3678 
3679     if (value->unit == CSSParserValue::Operator && value->iValue == '/') {
3680         // line-height
3681         value = m_valueList->next();
3682         if (!value)
3683             return false;
3684         if (value->id == CSSValueNormal) {
3685             // default value, nothing to do
3686         } else if (validUnit(value, FNumber | FLength | FPercent | FNonNeg, m_strict))
3687             font->lineHeight = primitiveValueCache()->createValue(value->fValue, (CSSPrimitiveValue::UnitTypes) value->unit);
3688         else
3689             return false;
3690         value = m_valueList->next();
3691         if (!value)
3692             return false;
3693     }
3694 
3695     if (!font->lineHeight)
3696         font->lineHeight = primitiveValueCache()->createIdentifierValue(CSSValueNormal);
3697 
3698     // font family must come now
3699     font->family = parseFontFamily();
3700 
3701     if (m_valueList->current() || !font->family)
3702         return false;
3703 
3704     addProperty(CSSPropertyFont, font.release(), important);
3705     return true;
3706 }
3707 
parseFontFamily()3708 PassRefPtr<CSSValueList> CSSParser::parseFontFamily()
3709 {
3710     RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
3711     CSSParserValue* value = m_valueList->current();
3712 
3713     FontFamilyValue* currFamily = 0;
3714     while (value) {
3715         CSSParserValue* nextValue = m_valueList->next();
3716         bool nextValBreaksFont = !nextValue ||
3717                                  (nextValue->unit == CSSParserValue::Operator && nextValue->iValue == ',');
3718         bool nextValIsFontName = nextValue &&
3719             ((nextValue->id >= CSSValueSerif && nextValue->id <= CSSValueWebkitBody) ||
3720             (nextValue->unit == CSSPrimitiveValue::CSS_STRING || nextValue->unit == CSSPrimitiveValue::CSS_IDENT));
3721 
3722         if (value->id >= CSSValueSerif && value->id <= CSSValueWebkitBody) {
3723             if (currFamily)
3724                 currFamily->appendSpaceSeparated(value->string.characters, value->string.length);
3725             else if (nextValBreaksFont || !nextValIsFontName)
3726                 list->append(primitiveValueCache()->createIdentifierValue(value->id));
3727             else {
3728                 RefPtr<FontFamilyValue> newFamily = FontFamilyValue::create(value->string);
3729                 currFamily = newFamily.get();
3730                 list->append(newFamily.release());
3731             }
3732         } else if (value->unit == CSSPrimitiveValue::CSS_STRING) {
3733             // Strings never share in a family name.
3734             currFamily = 0;
3735             list->append(FontFamilyValue::create(value->string));
3736         } else if (value->unit == CSSPrimitiveValue::CSS_IDENT) {
3737             if (currFamily)
3738                 currFamily->appendSpaceSeparated(value->string.characters, value->string.length);
3739             else if (nextValBreaksFont || !nextValIsFontName)
3740                 list->append(FontFamilyValue::create(value->string));
3741             else {
3742                 RefPtr<FontFamilyValue> newFamily = FontFamilyValue::create(value->string);
3743                 currFamily = newFamily.get();
3744                 list->append(newFamily.release());
3745             }
3746         } else {
3747             break;
3748         }
3749 
3750         if (!nextValue)
3751             break;
3752 
3753         if (nextValBreaksFont) {
3754             value = m_valueList->next();
3755             currFamily = 0;
3756         }
3757         else if (nextValIsFontName)
3758             value = nextValue;
3759         else
3760             break;
3761     }
3762     if (!list->length())
3763         list = 0;
3764     return list.release();
3765 }
3766 
parseFontVariant(bool important)3767 bool CSSParser::parseFontVariant(bool important)
3768 {
3769     RefPtr<CSSValueList> values;
3770     if (m_valueList->size() > 1)
3771         values = CSSValueList::createCommaSeparated();
3772     CSSParserValue* val;
3773     bool expectComma = false;
3774     while ((val = m_valueList->current())) {
3775         RefPtr<CSSPrimitiveValue> parsedValue;
3776         if (!expectComma) {
3777             expectComma = true;
3778             if (val->id == CSSValueNormal || val->id == CSSValueSmallCaps)
3779                 parsedValue = primitiveValueCache()->createIdentifierValue(val->id);
3780             else if (val->id == CSSValueAll && !values) {
3781                 // 'all' is only allowed in @font-face and with no other values. Make a value list to
3782                 // indicate that we are in the @font-face case.
3783                 values = CSSValueList::createCommaSeparated();
3784                 parsedValue = primitiveValueCache()->createIdentifierValue(val->id);
3785             }
3786         } else if (val->unit == CSSParserValue::Operator && val->iValue == ',') {
3787             expectComma = false;
3788             m_valueList->next();
3789             continue;
3790         }
3791 
3792         if (!parsedValue)
3793             return false;
3794 
3795         m_valueList->next();
3796 
3797         if (values)
3798             values->append(parsedValue.release());
3799         else {
3800             addProperty(CSSPropertyFontVariant, parsedValue.release(), important);
3801             return true;
3802         }
3803     }
3804 
3805     if (values && values->length()) {
3806         m_hasFontFaceOnlyValues = true;
3807         addProperty(CSSPropertyFontVariant, values.release(), important);
3808         return true;
3809     }
3810 
3811     return false;
3812 }
3813 
parseFontWeight(bool important)3814 bool CSSParser::parseFontWeight(bool important)
3815 {
3816     if (m_valueList->size() != 1)
3817         return false;
3818 
3819     CSSParserValue* value = m_valueList->current();
3820     if ((value->id >= CSSValueNormal) && (value->id <= CSSValue900)) {
3821         addProperty(CSSPropertyFontWeight, primitiveValueCache()->createIdentifierValue(value->id), important);
3822         return true;
3823     }
3824 
3825     if (validUnit(value, FInteger | FNonNeg, false)) {
3826         int weight = static_cast<int>(value->fValue);
3827             if (!(weight % 100) && weight >= 100 && weight <= 900)
3828                 addProperty(CSSPropertyFontWeight, primitiveValueCache()->createIdentifierValue(CSSValue100 + weight / 100 - 1), important);
3829         return true;
3830     }
3831 
3832     return false;
3833 }
3834 
isValidFormatFunction(CSSParserValue * val)3835 static bool isValidFormatFunction(CSSParserValue* val)
3836 {
3837     CSSParserValueList* args = val->function->args.get();
3838     return equalIgnoringCase(val->function->name, "format(") && (args->current()->unit == CSSPrimitiveValue::CSS_STRING || args->current()->unit == CSSPrimitiveValue::CSS_IDENT);
3839 }
3840 
parseFontFaceSrc()3841 bool CSSParser::parseFontFaceSrc()
3842 {
3843     RefPtr<CSSValueList> values(CSSValueList::createCommaSeparated());
3844     CSSParserValue* val;
3845     bool expectComma = false;
3846     bool allowFormat = false;
3847     bool failed = false;
3848     RefPtr<CSSFontFaceSrcValue> uriValue;
3849     while ((val = m_valueList->current())) {
3850         RefPtr<CSSFontFaceSrcValue> parsedValue;
3851         if (val->unit == CSSPrimitiveValue::CSS_URI && !expectComma && m_styleSheet) {
3852             // FIXME: The completeURL call should be done when using the CSSFontFaceSrcValue,
3853             // not when creating it.
3854             parsedValue = CSSFontFaceSrcValue::create(m_styleSheet->completeURL(val->string));
3855             uriValue = parsedValue;
3856             allowFormat = true;
3857             expectComma = true;
3858         } else if (val->unit == CSSParserValue::Function) {
3859             // There are two allowed functions: local() and format().
3860             CSSParserValueList* args = val->function->args.get();
3861             if (args && args->size() == 1) {
3862                 if (equalIgnoringCase(val->function->name, "local(") && !expectComma && (args->current()->unit == CSSPrimitiveValue::CSS_STRING || args->current()->unit == CSSPrimitiveValue::CSS_IDENT)) {
3863                     expectComma = true;
3864                     allowFormat = false;
3865                     CSSParserValue* a = args->current();
3866                     uriValue.clear();
3867                     parsedValue = CSSFontFaceSrcValue::createLocal(a->string);
3868                 } else if (allowFormat && uriValue && isValidFormatFunction(val)) {
3869                     expectComma = true;
3870                     allowFormat = false;
3871                     uriValue->setFormat(args->current()->string);
3872                     uriValue.clear();
3873                     m_valueList->next();
3874                     continue;
3875                 }
3876             }
3877         } else if (val->unit == CSSParserValue::Operator && val->iValue == ',' && expectComma) {
3878             expectComma = false;
3879             allowFormat = false;
3880             uriValue.clear();
3881             m_valueList->next();
3882             continue;
3883         }
3884 
3885         if (parsedValue)
3886             values->append(parsedValue.release());
3887         else {
3888             failed = true;
3889             break;
3890         }
3891         m_valueList->next();
3892     }
3893 
3894     if (values->length() && !failed) {
3895         addProperty(CSSPropertySrc, values.release(), m_important);
3896         m_valueList->next();
3897         return true;
3898     }
3899 
3900     return false;
3901 }
3902 
parseFontFaceUnicodeRange()3903 bool CSSParser::parseFontFaceUnicodeRange()
3904 {
3905     RefPtr<CSSValueList> values = CSSValueList::createCommaSeparated();
3906     bool failed = false;
3907     bool operatorExpected = false;
3908     for (; m_valueList->current(); m_valueList->next(), operatorExpected = !operatorExpected) {
3909         if (operatorExpected) {
3910             if (m_valueList->current()->unit == CSSParserValue::Operator && m_valueList->current()->iValue == ',')
3911                 continue;
3912             failed = true;
3913             break;
3914         }
3915         if (m_valueList->current()->unit != CSSPrimitiveValue::CSS_UNICODE_RANGE) {
3916             failed = true;
3917             break;
3918         }
3919 
3920         String rangeString = m_valueList->current()->string;
3921         UChar32 from = 0;
3922         UChar32 to = 0;
3923         unsigned length = rangeString.length();
3924 
3925         if (length < 3) {
3926             failed = true;
3927             break;
3928         }
3929 
3930         unsigned i = 2;
3931         while (i < length) {
3932             UChar c = rangeString[i];
3933             if (c == '-' || c == '?')
3934                 break;
3935             from *= 16;
3936             if (c >= '0' && c <= '9')
3937                 from += c - '0';
3938             else if (c >= 'A' && c <= 'F')
3939                 from += 10 + c - 'A';
3940             else if (c >= 'a' && c <= 'f')
3941                 from += 10 + c - 'a';
3942             else {
3943                 failed = true;
3944                 break;
3945             }
3946             i++;
3947         }
3948         if (failed)
3949             break;
3950 
3951         if (i == length)
3952             to = from;
3953         else if (rangeString[i] == '?') {
3954             unsigned span = 1;
3955             while (i < length && rangeString[i] == '?') {
3956                 span *= 16;
3957                 from *= 16;
3958                 i++;
3959             }
3960             if (i < length)
3961                 failed = true;
3962             to = from + span - 1;
3963         } else {
3964             if (length < i + 2) {
3965                 failed = true;
3966                 break;
3967             }
3968             i++;
3969             while (i < length) {
3970                 UChar c = rangeString[i];
3971                 to *= 16;
3972                 if (c >= '0' && c <= '9')
3973                     to += c - '0';
3974                 else if (c >= 'A' && c <= 'F')
3975                     to += 10 + c - 'A';
3976                 else if (c >= 'a' && c <= 'f')
3977                     to += 10 + c - 'a';
3978                 else {
3979                     failed = true;
3980                     break;
3981                 }
3982                 i++;
3983             }
3984             if (failed)
3985                 break;
3986         }
3987         if (from <= to)
3988             values->append(CSSUnicodeRangeValue::create(from, to));
3989     }
3990     if (failed || !values->length())
3991         return false;
3992     addProperty(CSSPropertyUnicodeRange, values.release(), m_important);
3993     return true;
3994 }
3995 
3996 // Returns the number of characters which form a valid double
3997 // and are terminated by the given terminator character
checkForValidDouble(const UChar * string,const UChar * end,const char terminator)3998 static int checkForValidDouble(const UChar* string, const UChar* end, const char terminator)
3999 {
4000     int length = end - string;
4001     if (length < 1)
4002         return 0;
4003 
4004     bool decimalMarkSeen = false;
4005     int processedLength = 0;
4006 
4007     for (int i = 0; i < length; ++i) {
4008         if (string[i] == terminator) {
4009             processedLength = i;
4010             break;
4011         }
4012         if (!isASCIIDigit(string[i])) {
4013             if (!decimalMarkSeen && string[i] == '.')
4014                 decimalMarkSeen = true;
4015             else
4016                 return 0;
4017         }
4018     }
4019 
4020     if (decimalMarkSeen && processedLength == 1)
4021         return 0;
4022 
4023     return processedLength;
4024 }
4025 
4026 // Returns the number of characters consumed for parsing a valid double
4027 // terminated by the given terminator character
parseDouble(const UChar * string,const UChar * end,const char terminator,double & value)4028 static int parseDouble(const UChar* string, const UChar* end, const char terminator, double& value)
4029 {
4030     int length = checkForValidDouble(string, end, terminator);
4031     if (!length)
4032         return 0;
4033 
4034     int position = 0;
4035     double localValue = 0;
4036 
4037     // The consumed characters here are guaranteed to be
4038     // ASCII digits with or without a decimal mark
4039     for (; position < length; ++position) {
4040         if (string[position] == '.')
4041             break;
4042         localValue = localValue * 10 + string[position] - '0';
4043     }
4044 
4045     if (++position == length) {
4046         value = localValue;
4047         return length;
4048     }
4049 
4050     double fraction = 0;
4051     double scale = 1;
4052 
4053     while (position < length && scale < MAX_SCALE) {
4054         fraction = fraction * 10 + string[position++] - '0';
4055         scale *= 10;
4056     }
4057 
4058     value = localValue + fraction / scale;
4059     return length;
4060 }
4061 
parseColorIntOrPercentage(const UChar * & string,const UChar * end,const char terminator,CSSPrimitiveValue::UnitTypes & expect,int & value)4062 static bool parseColorIntOrPercentage(const UChar*& string, const UChar* end, const char terminator, CSSPrimitiveValue::UnitTypes& expect, int& value)
4063 {
4064     const UChar* current = string;
4065     double localValue = 0;
4066     bool negative = false;
4067     while (current != end && isHTMLSpace(*current))
4068         current++;
4069     if (current != end && *current == '-') {
4070         negative = true;
4071         current++;
4072     }
4073     if (current == end || !isASCIIDigit(*current))
4074         return false;
4075     while (current != end && isASCIIDigit(*current)) {
4076         double newValue = localValue * 10 + *current++ - '0';
4077         if (newValue >= 255) {
4078             // Clamp values at 255.
4079             localValue = 255;
4080             while (current != end && isASCIIDigit(*current))
4081                 ++current;
4082             break;
4083         }
4084         localValue = newValue;
4085     }
4086 
4087     if (current == end)
4088         return false;
4089 
4090     if (expect == CSSPrimitiveValue::CSS_NUMBER && (*current == '.' || *current == '%'))
4091         return false;
4092 
4093     if (*current == '.') {
4094         // We already parsed the integral part, try to parse
4095         // the fraction part of the percentage value.
4096         double percentage = 0;
4097         int numCharactersParsed = parseDouble(current, end, '%', percentage);
4098         if (!numCharactersParsed)
4099             return false;
4100         current += numCharactersParsed;
4101         if (*current != '%')
4102             return false;
4103         localValue += percentage;
4104     }
4105 
4106     if (expect == CSSPrimitiveValue::CSS_PERCENTAGE && *current != '%')
4107         return false;
4108 
4109     if (*current == '%') {
4110         expect = CSSPrimitiveValue::CSS_PERCENTAGE;
4111         localValue = localValue / 100.0 * 256.0;
4112         // Clamp values at 255 for percentages over 100%
4113         if (localValue > 255)
4114             localValue = 255;
4115         current++;
4116     } else
4117         expect = CSSPrimitiveValue::CSS_NUMBER;
4118 
4119     while (current != end && isHTMLSpace(*current))
4120         current++;
4121     if (current == end || *current++ != terminator)
4122         return false;
4123     // Clamp negative values at zero.
4124     value = negative ? 0 : static_cast<int>(localValue);
4125     string = current;
4126     return true;
4127 }
4128 
isTenthAlpha(const UChar * string,const int length)4129 static inline bool isTenthAlpha(const UChar* string, const int length)
4130 {
4131     // "0.X"
4132     if (length == 3 && string[0] == '0' && string[1] == '.' && isASCIIDigit(string[2]))
4133         return true;
4134 
4135     // ".X"
4136     if (length == 2 && string[0] == '.' && isASCIIDigit(string[1]))
4137         return true;
4138 
4139     return false;
4140 }
4141 
parseAlphaValue(const UChar * & string,const UChar * end,const char terminator,int & value)4142 static inline bool parseAlphaValue(const UChar*& string, const UChar* end, const char terminator, int& value)
4143 {
4144     while (string != end && isHTMLSpace(*string))
4145         string++;
4146 
4147     bool negative = false;
4148 
4149     if (string != end && *string == '-') {
4150         negative = true;
4151         string++;
4152     }
4153 
4154     value = 0;
4155 
4156     int length = end - string;
4157     if (length < 2)
4158         return false;
4159 
4160     if (string[length - 1] != terminator)
4161         return false;
4162 
4163     if (string[0] != '0' && string[0] != '1' && string[0] != '.') {
4164         if (checkForValidDouble(string, end, terminator)) {
4165             value = negative ? 0 : 255;
4166             string = end;
4167             return true;
4168         }
4169         return false;
4170     }
4171 
4172     if (length == 2 && string[0] != '.') {
4173         value = !negative && string[0] == '1' ? 255 : 0;
4174         string = end;
4175         return true;
4176     }
4177 
4178     if (isTenthAlpha(string, length - 1)) {
4179         static const int tenthAlphaValues[] = { 0, 25, 51, 76, 102, 127, 153, 179, 204, 230 };
4180         value = negative ? 0 : tenthAlphaValues[string[length - 2] - '0'];
4181         string = end;
4182         return true;
4183     }
4184 
4185     double alpha = 0;
4186     if (!parseDouble(string, end, terminator, alpha))
4187         return false;
4188     value = negative ? 0 : static_cast<int>(alpha * nextafter(256.0, 0.0));
4189     string = end;
4190     return true;
4191 }
4192 
mightBeRGBA(const UChar * characters,unsigned length)4193 static inline bool mightBeRGBA(const UChar* characters, unsigned length)
4194 {
4195     if (length < 5)
4196         return false;
4197     return characters[4] == '('
4198         && (characters[0] | 0x20) == 'r'
4199         && (characters[1] | 0x20) == 'g'
4200         && (characters[2] | 0x20) == 'b'
4201         && (characters[3] | 0x20) == 'a';
4202 }
4203 
mightBeRGB(const UChar * characters,unsigned length)4204 static inline bool mightBeRGB(const UChar* characters, unsigned length)
4205 {
4206     if (length < 4)
4207         return false;
4208     return characters[3] == '('
4209         && (characters[0] | 0x20) == 'r'
4210         && (characters[1] | 0x20) == 'g'
4211         && (characters[2] | 0x20) == 'b';
4212 }
4213 
parseColor(const String & name,RGBA32 & rgb,bool strict)4214 bool CSSParser::parseColor(const String &name, RGBA32& rgb, bool strict)
4215 {
4216     const UChar* characters = name.characters();
4217     unsigned length = name.length();
4218     CSSPrimitiveValue::UnitTypes expect = CSSPrimitiveValue::CSS_UNKNOWN;
4219 
4220     if (!strict && length >= 3) {
4221         if (name[0] == '#') {
4222             if (Color::parseHexColor(characters + 1, length - 1, rgb))
4223                 return true;
4224         } else {
4225             if (Color::parseHexColor(characters, length, rgb))
4226                 return true;
4227         }
4228     }
4229 
4230     // Try rgba() syntax.
4231     if (mightBeRGBA(characters, length)) {
4232         const UChar* current = characters + 5;
4233         const UChar* end = characters + length;
4234         int red;
4235         int green;
4236         int blue;
4237         int alpha;
4238 
4239         if (!parseColorIntOrPercentage(current, end, ',', expect, red))
4240             return false;
4241         if (!parseColorIntOrPercentage(current, end, ',', expect, green))
4242             return false;
4243         if (!parseColorIntOrPercentage(current, end, ',', expect, blue))
4244             return false;
4245         if (!parseAlphaValue(current, end, ')', alpha))
4246             return false;
4247         if (current != end)
4248             return false;
4249         rgb = makeRGBA(red, green, blue, alpha);
4250         return true;
4251     }
4252 
4253     // Try rgb() syntax.
4254     if (mightBeRGB(characters, length)) {
4255         const UChar* current = characters + 4;
4256         const UChar* end = characters + length;
4257         int red;
4258         int green;
4259         int blue;
4260         if (!parseColorIntOrPercentage(current, end, ',', expect, red))
4261             return false;
4262         if (!parseColorIntOrPercentage(current, end, ',', expect, green))
4263             return false;
4264         if (!parseColorIntOrPercentage(current, end, ')', expect, blue))
4265             return false;
4266         if (current != end)
4267             return false;
4268         rgb = makeRGB(red, green, blue);
4269         return true;
4270     }
4271 
4272     // Try named colors.
4273     Color tc;
4274     tc.setNamedColor(name);
4275     if (tc.isValid()) {
4276         rgb = tc.rgb();
4277         return true;
4278     }
4279     return false;
4280 }
4281 
colorIntFromValue(CSSParserValue * v)4282 static inline int colorIntFromValue(CSSParserValue* v)
4283 {
4284     if (v->fValue <= 0.0)
4285         return 0;
4286 
4287     if (v->unit == CSSPrimitiveValue::CSS_PERCENTAGE) {
4288         if (v->fValue >= 100.0)
4289             return 255;
4290         return static_cast<int>(v->fValue * 256.0 / 100.0);
4291     }
4292 
4293     if (v->fValue >= 255.0)
4294         return 255;
4295 
4296     return static_cast<int>(v->fValue);
4297 }
4298 
parseColorParameters(CSSParserValue * value,int * colorArray,bool parseAlpha)4299 bool CSSParser::parseColorParameters(CSSParserValue* value, int* colorArray, bool parseAlpha)
4300 {
4301     CSSParserValueList* args = value->function->args.get();
4302     CSSParserValue* v = args->current();
4303     Units unitType = FUnknown;
4304     // Get the first value and its type
4305     if (validUnit(v, FInteger, true))
4306         unitType = FInteger;
4307     else if (validUnit(v, FPercent, true))
4308         unitType = FPercent;
4309     else
4310         return false;
4311     colorArray[0] = colorIntFromValue(v);
4312     for (int i = 1; i < 3; i++) {
4313         v = args->next();
4314         if (v->unit != CSSParserValue::Operator && v->iValue != ',')
4315             return false;
4316         v = args->next();
4317         if (!validUnit(v, unitType, true))
4318             return false;
4319         colorArray[i] = colorIntFromValue(v);
4320     }
4321     if (parseAlpha) {
4322         v = args->next();
4323         if (v->unit != CSSParserValue::Operator && v->iValue != ',')
4324             return false;
4325         v = args->next();
4326         if (!validUnit(v, FNumber, true))
4327             return false;
4328         // Convert the floating pointer number of alpha to an integer in the range [0, 256),
4329         // with an equal distribution across all 256 values.
4330         colorArray[3] = static_cast<int>(max(0.0, min(1.0, v->fValue)) * nextafter(256.0, 0.0));
4331     }
4332     return true;
4333 }
4334 
4335 // The CSS3 specification defines the format of a HSL color as
4336 // hsl(<number>, <percent>, <percent>)
4337 // and with alpha, the format is
4338 // hsla(<number>, <percent>, <percent>, <number>)
4339 // The first value, HUE, is in an angle with a value between 0 and 360
parseHSLParameters(CSSParserValue * value,double * colorArray,bool parseAlpha)4340 bool CSSParser::parseHSLParameters(CSSParserValue* value, double* colorArray, bool parseAlpha)
4341 {
4342     CSSParserValueList* args = value->function->args.get();
4343     CSSParserValue* v = args->current();
4344     // Get the first value
4345     if (!validUnit(v, FNumber, true))
4346         return false;
4347     // normalize the Hue value and change it to be between 0 and 1.0
4348     colorArray[0] = (((static_cast<int>(v->fValue) % 360) + 360) % 360) / 360.0;
4349     for (int i = 1; i < 3; i++) {
4350         v = args->next();
4351         if (v->unit != CSSParserValue::Operator && v->iValue != ',')
4352             return false;
4353         v = args->next();
4354         if (!validUnit(v, FPercent, true))
4355             return false;
4356         colorArray[i] = max(0.0, min(100.0, v->fValue)) / 100.0; // needs to be value between 0 and 1.0
4357     }
4358     if (parseAlpha) {
4359         v = args->next();
4360         if (v->unit != CSSParserValue::Operator && v->iValue != ',')
4361             return false;
4362         v = args->next();
4363         if (!validUnit(v, FNumber, true))
4364             return false;
4365         colorArray[3] = max(0.0, min(1.0, v->fValue));
4366     }
4367     return true;
4368 }
4369 
parseColor(CSSParserValue * value)4370 PassRefPtr<CSSPrimitiveValue> CSSParser::parseColor(CSSParserValue* value)
4371 {
4372     RGBA32 c = Color::transparent;
4373     if (!parseColorFromValue(value ? value : m_valueList->current(), c))
4374         return 0;
4375     return primitiveValueCache()->createColorValue(c);
4376 }
4377 
parseColorFromValue(CSSParserValue * value,RGBA32 & c)4378 bool CSSParser::parseColorFromValue(CSSParserValue* value, RGBA32& c)
4379 {
4380     if (!m_strict && value->unit == CSSPrimitiveValue::CSS_NUMBER &&
4381         value->fValue >= 0. && value->fValue < 1000000.) {
4382         String str = String::format("%06d", (int)(value->fValue+.5));
4383         if (!CSSParser::parseColor(str, c, m_strict))
4384             return false;
4385     } else if (value->unit == CSSPrimitiveValue::CSS_PARSER_HEXCOLOR ||
4386                 value->unit == CSSPrimitiveValue::CSS_IDENT ||
4387                 (!m_strict && value->unit == CSSPrimitiveValue::CSS_DIMENSION)) {
4388         if (!CSSParser::parseColor(value->string, c, m_strict && value->unit == CSSPrimitiveValue::CSS_IDENT))
4389             return false;
4390     } else if (value->unit == CSSParserValue::Function &&
4391                 value->function->args != 0 &&
4392                 value->function->args->size() == 5 /* rgb + two commas */ &&
4393                 equalIgnoringCase(value->function->name, "rgb(")) {
4394         int colorValues[3];
4395         if (!parseColorParameters(value, colorValues, false))
4396             return false;
4397         c = makeRGB(colorValues[0], colorValues[1], colorValues[2]);
4398     } else {
4399         if (value->unit == CSSParserValue::Function &&
4400                 value->function->args != 0 &&
4401                 value->function->args->size() == 7 /* rgba + three commas */ &&
4402                 equalIgnoringCase(value->function->name, "rgba(")) {
4403             int colorValues[4];
4404             if (!parseColorParameters(value, colorValues, true))
4405                 return false;
4406             c = makeRGBA(colorValues[0], colorValues[1], colorValues[2], colorValues[3]);
4407         } else if (value->unit == CSSParserValue::Function &&
4408                     value->function->args != 0 &&
4409                     value->function->args->size() == 5 /* hsl + two commas */ &&
4410                     equalIgnoringCase(value->function->name, "hsl(")) {
4411             double colorValues[3];
4412             if (!parseHSLParameters(value, colorValues, false))
4413                 return false;
4414             c = makeRGBAFromHSLA(colorValues[0], colorValues[1], colorValues[2], 1.0);
4415         } else if (value->unit == CSSParserValue::Function &&
4416                     value->function->args != 0 &&
4417                     value->function->args->size() == 7 /* hsla + three commas */ &&
4418                     equalIgnoringCase(value->function->name, "hsla(")) {
4419             double colorValues[4];
4420             if (!parseHSLParameters(value, colorValues, true))
4421                 return false;
4422             c = makeRGBAFromHSLA(colorValues[0], colorValues[1], colorValues[2], colorValues[3]);
4423         } else
4424             return false;
4425     }
4426 
4427     return true;
4428 }
4429 
4430 // This class tracks parsing state for shadow values.  If it goes out of scope (e.g., due to an early return)
4431 // without the allowBreak bit being set, then it will clean up all of the objects and destroy them.
4432 struct ShadowParseContext {
ShadowParseContextWebCore::ShadowParseContext4433     ShadowParseContext(CSSPropertyID prop, CSSPrimitiveValueCache* primitiveValueCache)
4434         : property(prop)
4435         , m_primitiveValueCache(primitiveValueCache)
4436         , allowX(true)
4437         , allowY(false)
4438         , allowBlur(false)
4439         , allowSpread(false)
4440         , allowColor(true)
4441         , allowStyle(prop == CSSPropertyWebkitBoxShadow || prop == CSSPropertyBoxShadow)
4442         , allowBreak(true)
4443     {
4444     }
4445 
allowLengthWebCore::ShadowParseContext4446     bool allowLength() { return allowX || allowY || allowBlur || allowSpread; }
4447 
commitValueWebCore::ShadowParseContext4448     void commitValue()
4449     {
4450         // Handle the ,, case gracefully by doing nothing.
4451         if (x || y || blur || spread || color || style) {
4452             if (!values)
4453                 values = CSSValueList::createCommaSeparated();
4454 
4455             // Construct the current shadow value and add it to the list.
4456             values->append(ShadowValue::create(x.release(), y.release(), blur.release(), spread.release(), style.release(), color.release()));
4457         }
4458 
4459         // Now reset for the next shadow value.
4460         x = 0;
4461         y = 0;
4462         blur = 0;
4463         spread = 0;
4464         style = 0;
4465         color = 0;
4466 
4467         allowX = true;
4468         allowColor = true;
4469         allowBreak = true;
4470         allowY = false;
4471         allowBlur = false;
4472         allowSpread = false;
4473         allowStyle = property == CSSPropertyWebkitBoxShadow || property == CSSPropertyBoxShadow;
4474     }
4475 
commitLengthWebCore::ShadowParseContext4476     void commitLength(CSSParserValue* v)
4477     {
4478         RefPtr<CSSPrimitiveValue> val = m_primitiveValueCache->createValue(v->fValue, (CSSPrimitiveValue::UnitTypes)v->unit);
4479 
4480         if (allowX) {
4481             x = val.release();
4482             allowX = false;
4483             allowY = true;
4484             allowColor = false;
4485             allowStyle = false;
4486             allowBreak = false;
4487         } else if (allowY) {
4488             y = val.release();
4489             allowY = false;
4490             allowBlur = true;
4491             allowColor = true;
4492             allowStyle = property == CSSPropertyWebkitBoxShadow || property == CSSPropertyBoxShadow;
4493             allowBreak = true;
4494         } else if (allowBlur) {
4495             blur = val.release();
4496             allowBlur = false;
4497             allowSpread = property == CSSPropertyWebkitBoxShadow || property == CSSPropertyBoxShadow;
4498         } else if (allowSpread) {
4499             spread = val.release();
4500             allowSpread = false;
4501         }
4502     }
4503 
commitColorWebCore::ShadowParseContext4504     void commitColor(PassRefPtr<CSSPrimitiveValue> val)
4505     {
4506         color = val;
4507         allowColor = false;
4508         if (allowX) {
4509             allowStyle = false;
4510             allowBreak = false;
4511         } else {
4512             allowBlur = false;
4513             allowSpread = false;
4514             allowStyle = property == CSSPropertyWebkitBoxShadow || property == CSSPropertyBoxShadow;
4515         }
4516     }
4517 
commitStyleWebCore::ShadowParseContext4518     void commitStyle(CSSParserValue* v)
4519     {
4520         style = m_primitiveValueCache->createIdentifierValue(v->id);
4521         allowStyle = false;
4522         if (allowX)
4523             allowBreak = false;
4524         else {
4525             allowBlur = false;
4526             allowSpread = false;
4527             allowColor = false;
4528         }
4529     }
4530 
4531     CSSPropertyID property;
4532     CSSPrimitiveValueCache* m_primitiveValueCache;
4533 
4534     RefPtr<CSSValueList> values;
4535     RefPtr<CSSPrimitiveValue> x;
4536     RefPtr<CSSPrimitiveValue> y;
4537     RefPtr<CSSPrimitiveValue> blur;
4538     RefPtr<CSSPrimitiveValue> spread;
4539     RefPtr<CSSPrimitiveValue> style;
4540     RefPtr<CSSPrimitiveValue> color;
4541 
4542     bool allowX;
4543     bool allowY;
4544     bool allowBlur;
4545     bool allowSpread;
4546     bool allowColor;
4547     bool allowStyle; // inset or not.
4548     bool allowBreak;
4549 };
4550 
parseShadow(int propId,bool important)4551 bool CSSParser::parseShadow(int propId, bool important)
4552 {
4553     ShadowParseContext context(static_cast<CSSPropertyID>(propId), primitiveValueCache());
4554     CSSParserValue* val;
4555     while ((val = m_valueList->current())) {
4556         // Check for a comma break first.
4557         if (val->unit == CSSParserValue::Operator) {
4558             if (val->iValue != ',' || !context.allowBreak)
4559                 // Other operators aren't legal or we aren't done with the current shadow
4560                 // value.  Treat as invalid.
4561                 return false;
4562 #if ENABLE(SVG)
4563             // -webkit-svg-shadow does not support multiple values.
4564             if (static_cast<CSSPropertyID>(propId) == CSSPropertyWebkitSvgShadow)
4565                 return false;
4566 #endif
4567             // The value is good.  Commit it.
4568             context.commitValue();
4569         } else if (validUnit(val, FLength, true)) {
4570             // We required a length and didn't get one. Invalid.
4571             if (!context.allowLength())
4572                 return false;
4573 
4574             // A length is allowed here.  Construct the value and add it.
4575             context.commitLength(val);
4576         } else if (val->id == CSSValueInset) {
4577             if (!context.allowStyle)
4578                 return false;
4579 
4580             context.commitStyle(val);
4581         } else {
4582             // The only other type of value that's ok is a color value.
4583             RefPtr<CSSPrimitiveValue> parsedColor;
4584             bool isColor = ((val->id >= CSSValueAqua && val->id <= CSSValueWindowtext) || val->id == CSSValueMenu ||
4585                             (val->id >= CSSValueWebkitFocusRingColor && val->id <= CSSValueWebkitText && !m_strict));
4586             if (isColor) {
4587                 if (!context.allowColor)
4588                     return false;
4589                 parsedColor = primitiveValueCache()->createIdentifierValue(val->id);
4590             }
4591 
4592             if (!parsedColor)
4593                 // It's not built-in. Try to parse it as a color.
4594                 parsedColor = parseColor(val);
4595 
4596             if (!parsedColor || !context.allowColor)
4597                 return false; // This value is not a color or length and is invalid or
4598                               // it is a color, but a color isn't allowed at this point.
4599 
4600             context.commitColor(parsedColor.release());
4601         }
4602 
4603         m_valueList->next();
4604     }
4605 
4606     if (context.allowBreak) {
4607         context.commitValue();
4608         if (context.values->length()) {
4609             addProperty(propId, context.values.release(), important);
4610             m_valueList->next();
4611             return true;
4612         }
4613     }
4614 
4615     return false;
4616 }
4617 
parseReflect(int propId,bool important)4618 bool CSSParser::parseReflect(int propId, bool important)
4619 {
4620     // box-reflect: <direction> <offset> <mask>
4621 
4622     // Direction comes first.
4623     CSSParserValue* val = m_valueList->current();
4624     CSSReflectionDirection direction;
4625     switch (val->id) {
4626         case CSSValueAbove:
4627             direction = ReflectionAbove;
4628             break;
4629         case CSSValueBelow:
4630             direction = ReflectionBelow;
4631             break;
4632         case CSSValueLeft:
4633             direction = ReflectionLeft;
4634             break;
4635         case CSSValueRight:
4636             direction = ReflectionRight;
4637             break;
4638         default:
4639             return false;
4640     }
4641 
4642     // The offset comes next.
4643     val = m_valueList->next();
4644     RefPtr<CSSPrimitiveValue> offset;
4645     if (!val)
4646         offset = primitiveValueCache()->createValue(0, CSSPrimitiveValue::CSS_PX);
4647     else {
4648         if (!validUnit(val, FLength | FPercent, m_strict))
4649             return false;
4650         offset = primitiveValueCache()->createValue(val->fValue, static_cast<CSSPrimitiveValue::UnitTypes>(val->unit));
4651     }
4652 
4653     // Now for the mask.
4654     RefPtr<CSSValue> mask;
4655     val = m_valueList->next();
4656     if (val) {
4657         if (!parseBorderImage(propId, important, mask))
4658             return false;
4659     }
4660 
4661     RefPtr<CSSReflectValue> reflectValue = CSSReflectValue::create(direction, offset.release(), mask.release());
4662     addProperty(propId, reflectValue.release(), important);
4663     m_valueList->next();
4664     return true;
4665 }
4666 
4667 struct BorderImageParseContext {
BorderImageParseContextWebCore::BorderImageParseContext4668     BorderImageParseContext(CSSPrimitiveValueCache* primitiveValueCache)
4669     : m_primitiveValueCache(primitiveValueCache)
4670     , m_allowBreak(false)
4671     , m_allowNumber(false)
4672     , m_allowSlash(false)
4673     , m_allowWidth(false)
4674     , m_allowRule(false)
4675     , m_borderTop(0)
4676     , m_borderRight(0)
4677     , m_borderBottom(0)
4678     , m_borderLeft(0)
4679     , m_horizontalRule(0)
4680     , m_verticalRule(0)
4681     {}
4682 
allowBreakWebCore::BorderImageParseContext4683     bool allowBreak() const { return m_allowBreak; }
allowNumberWebCore::BorderImageParseContext4684     bool allowNumber() const { return m_allowNumber; }
allowSlashWebCore::BorderImageParseContext4685     bool allowSlash() const { return m_allowSlash; }
allowWidthWebCore::BorderImageParseContext4686     bool allowWidth() const { return m_allowWidth; }
allowRuleWebCore::BorderImageParseContext4687     bool allowRule() const { return m_allowRule; }
4688 
commitImageWebCore::BorderImageParseContext4689     void commitImage(PassRefPtr<CSSValue> image) { m_image = image; m_allowNumber = true; }
commitNumberWebCore::BorderImageParseContext4690     void commitNumber(CSSParserValue* v)
4691     {
4692         PassRefPtr<CSSPrimitiveValue> val = m_primitiveValueCache->createValue(v->fValue, (CSSPrimitiveValue::UnitTypes)v->unit);
4693         if (!m_top)
4694             m_top = val;
4695         else if (!m_right)
4696             m_right = val;
4697         else if (!m_bottom)
4698             m_bottom = val;
4699         else {
4700             ASSERT(!m_left);
4701             m_left = val;
4702         }
4703 
4704         m_allowBreak = m_allowSlash = m_allowRule = true;
4705         m_allowNumber = !m_left;
4706     }
commitSlashWebCore::BorderImageParseContext4707     void commitSlash() { m_allowBreak = m_allowSlash = m_allowNumber = false; m_allowWidth = true; }
commitWidthWebCore::BorderImageParseContext4708     void commitWidth(CSSParserValue* val)
4709     {
4710         if (!m_borderTop)
4711             m_borderTop = val;
4712         else if (!m_borderRight)
4713             m_borderRight = val;
4714         else if (!m_borderBottom)
4715             m_borderBottom = val;
4716         else {
4717             ASSERT(!m_borderLeft);
4718             m_borderLeft = val;
4719         }
4720 
4721         m_allowBreak = m_allowRule = true;
4722         m_allowWidth = !m_borderLeft;
4723     }
commitRuleWebCore::BorderImageParseContext4724     void commitRule(int keyword)
4725     {
4726         if (!m_horizontalRule)
4727             m_horizontalRule = keyword;
4728         else if (!m_verticalRule)
4729             m_verticalRule = keyword;
4730         m_allowRule = !m_verticalRule;
4731     }
commitBorderImageWebCore::BorderImageParseContext4732     PassRefPtr<CSSValue> commitBorderImage(CSSParser* p, bool important)
4733     {
4734         // We need to clone and repeat values for any omissions.
4735         if (!m_right) {
4736             m_right = m_primitiveValueCache->createValue(m_top->getDoubleValue(), (CSSPrimitiveValue::UnitTypes)m_top->primitiveType());
4737             m_bottom = m_primitiveValueCache->createValue(m_top->getDoubleValue(), (CSSPrimitiveValue::UnitTypes)m_top->primitiveType());
4738             m_left = m_primitiveValueCache->createValue(m_top->getDoubleValue(), (CSSPrimitiveValue::UnitTypes)m_top->primitiveType());
4739         }
4740         if (!m_bottom) {
4741             m_bottom = m_primitiveValueCache->createValue(m_top->getDoubleValue(), (CSSPrimitiveValue::UnitTypes)m_top->primitiveType());
4742             m_left = m_primitiveValueCache->createValue(m_right->getDoubleValue(), (CSSPrimitiveValue::UnitTypes)m_right->primitiveType());
4743         }
4744         if (!m_left)
4745              m_left = m_primitiveValueCache->createValue(m_right->getDoubleValue(), (CSSPrimitiveValue::UnitTypes)m_right->primitiveType());
4746 
4747         // Now build a rect value to hold all four of our primitive values.
4748         RefPtr<Rect> rect = Rect::create();
4749         rect->setTop(m_top);
4750         rect->setRight(m_right);
4751         rect->setBottom(m_bottom);
4752         rect->setLeft(m_left);
4753 
4754         // Fill in STRETCH as the default if it wasn't specified.
4755         if (!m_horizontalRule)
4756             m_horizontalRule = CSSValueStretch;
4757 
4758         // The vertical rule should match the horizontal rule if unspecified.
4759         if (!m_verticalRule)
4760             m_verticalRule = m_horizontalRule;
4761 
4762         // Now we have to deal with the border widths.  The best way to deal with these is to actually put these values into a value
4763         // list and then make our parsing machinery do the parsing.
4764         if (m_borderTop) {
4765             CSSParserValueList newList;
4766             newList.addValue(*m_borderTop);
4767             if (m_borderRight)
4768                 newList.addValue(*m_borderRight);
4769             if (m_borderBottom)
4770                 newList.addValue(*m_borderBottom);
4771             if (m_borderLeft)
4772                 newList.addValue(*m_borderLeft);
4773             CSSParserValueList* oldList = p->m_valueList;
4774             p->m_valueList = &newList;
4775             p->parseValue(CSSPropertyBorderWidth, important);
4776             p->m_valueList = oldList;
4777         }
4778 
4779         // Make our new border image value now.
4780         return CSSBorderImageValue::create(m_image, rect.release(), m_horizontalRule, m_verticalRule);
4781     }
4782 
4783     CSSPrimitiveValueCache* m_primitiveValueCache;
4784 
4785     bool m_allowBreak;
4786     bool m_allowNumber;
4787     bool m_allowSlash;
4788     bool m_allowWidth;
4789     bool m_allowRule;
4790 
4791     RefPtr<CSSValue> m_image;
4792 
4793     RefPtr<CSSPrimitiveValue> m_top;
4794     RefPtr<CSSPrimitiveValue> m_right;
4795     RefPtr<CSSPrimitiveValue> m_bottom;
4796     RefPtr<CSSPrimitiveValue> m_left;
4797 
4798     CSSParserValue* m_borderTop;
4799     CSSParserValue* m_borderRight;
4800     CSSParserValue* m_borderBottom;
4801     CSSParserValue* m_borderLeft;
4802 
4803     int m_horizontalRule;
4804     int m_verticalRule;
4805 };
4806 
parseBorderImage(int propId,bool important,RefPtr<CSSValue> & result)4807 bool CSSParser::parseBorderImage(int propId, bool important, RefPtr<CSSValue>& result)
4808 {
4809     // Look for an image initially.  If the first value is not a URI, then we're done.
4810     BorderImageParseContext context(primitiveValueCache());
4811     CSSParserValue* val = m_valueList->current();
4812     if (val->unit == CSSPrimitiveValue::CSS_URI && m_styleSheet) {
4813         // FIXME: The completeURL call should be done when using the CSSImageValue,
4814         // not when creating it.
4815         context.commitImage(CSSImageValue::create(m_styleSheet->completeURL(val->string)));
4816     } else if (isGeneratedImageValue(val)) {
4817         RefPtr<CSSValue> value;
4818         if (parseGeneratedImage(value))
4819             context.commitImage(value);
4820         else
4821             return false;
4822     } else
4823         return false;
4824 
4825     while ((val = m_valueList->next())) {
4826         if (context.allowNumber() && validUnit(val, FInteger | FNonNeg | FPercent, true)) {
4827             context.commitNumber(val);
4828         } else if (propId == CSSPropertyWebkitBorderImage && context.allowSlash() && val->unit == CSSParserValue::Operator && val->iValue == '/') {
4829             context.commitSlash();
4830         } else if (context.allowWidth() &&
4831             (val->id == CSSValueThin || val->id == CSSValueMedium || val->id == CSSValueThick || validUnit(val, FLength, m_strict))) {
4832             context.commitWidth(val);
4833         } else if (context.allowRule() &&
4834             (val->id == CSSValueStretch || val->id == CSSValueRound || val->id == CSSValueRepeat)) {
4835             context.commitRule(val->id);
4836         } else {
4837             // Something invalid was encountered.
4838             return false;
4839         }
4840     }
4841 
4842     if (context.allowNumber() && propId != CSSPropertyWebkitBorderImage) {
4843         // Allow the slices to be omitted for images that don't fit to a border.  We just set the slices to be 0.
4844         context.m_top = primitiveValueCache()->createValue(0, CSSPrimitiveValue::CSS_NUMBER);
4845         context.m_allowBreak = true;
4846     }
4847 
4848     if (context.allowBreak()) {
4849         // Need to fully commit as a single value.
4850         result = context.commitBorderImage(this, important);
4851         return true;
4852     }
4853 
4854     return false;
4855 }
4856 
completeBorderRadii(RefPtr<CSSPrimitiveValue> radii[4])4857 static void completeBorderRadii(RefPtr<CSSPrimitiveValue> radii[4])
4858 {
4859     if (radii[3])
4860         return;
4861     if (!radii[2]) {
4862         if (!radii[1])
4863             radii[1] = radii[0];
4864         radii[2] = radii[0];
4865     }
4866     radii[3] = radii[1];
4867 }
4868 
parseBorderRadius(int propId,bool important)4869 bool CSSParser::parseBorderRadius(int propId, bool important)
4870 {
4871     unsigned num = m_valueList->size();
4872     if (num > 9)
4873         return false;
4874 
4875     ShorthandScope scope(this, propId);
4876     RefPtr<CSSPrimitiveValue> radii[2][4];
4877 
4878     unsigned indexAfterSlash = 0;
4879     for (unsigned i = 0; i < num; ++i) {
4880         CSSParserValue* value = m_valueList->valueAt(i);
4881         if (value->unit == CSSParserValue::Operator) {
4882             if (value->iValue != '/')
4883                 return false;
4884 
4885             if (!i || indexAfterSlash || i + 1 == num || num > i + 5)
4886                 return false;
4887 
4888             indexAfterSlash = i + 1;
4889             completeBorderRadii(radii[0]);
4890             continue;
4891         }
4892 
4893         if (i - indexAfterSlash >= 4)
4894             return false;
4895 
4896         if (!validUnit(value, FLength | FPercent, m_strict))
4897             return false;
4898 
4899         RefPtr<CSSPrimitiveValue> radius = primitiveValueCache()->createValue(value->fValue, static_cast<CSSPrimitiveValue::UnitTypes>(value->unit));
4900 
4901         if (!indexAfterSlash) {
4902             radii[0][i] = radius;
4903 
4904             // Legacy syntax: -webkit-border-radius: l1 l2; is equivalent to border-radius: l1 / l2;
4905             if (num == 2 && propId == CSSPropertyWebkitBorderRadius) {
4906                 indexAfterSlash = 1;
4907                 completeBorderRadii(radii[0]);
4908             }
4909         } else
4910             radii[1][i - indexAfterSlash] = radius.release();
4911     }
4912 
4913     if (!indexAfterSlash) {
4914         completeBorderRadii(radii[0]);
4915         for (unsigned i = 0; i < 4; ++i)
4916             radii[1][i] = radii[0][i];
4917     } else
4918         completeBorderRadii(radii[1]);
4919 
4920     m_implicitShorthand = true;
4921     addProperty(CSSPropertyBorderTopLeftRadius, primitiveValueCache()->createValue(Pair::create(radii[0][0].release(), radii[1][0].release())), important);
4922     addProperty(CSSPropertyBorderTopRightRadius, primitiveValueCache()->createValue(Pair::create(radii[0][1].release(), radii[1][1].release())), important);
4923     addProperty(CSSPropertyBorderBottomRightRadius, primitiveValueCache()->createValue(Pair::create(radii[0][2].release(), radii[1][2].release())), important);
4924     addProperty(CSSPropertyBorderBottomLeftRadius, primitiveValueCache()->createValue(Pair::create(radii[0][3].release(), radii[1][3].release())), important);
4925     m_implicitShorthand = false;
4926     return true;
4927 }
4928 
parseCounter(int propId,int defaultValue,bool important)4929 bool CSSParser::parseCounter(int propId, int defaultValue, bool important)
4930 {
4931     enum { ID, VAL } state = ID;
4932 
4933     RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
4934     RefPtr<CSSPrimitiveValue> counterName;
4935 
4936     while (true) {
4937         CSSParserValue* val = m_valueList->current();
4938         switch (state) {
4939             case ID:
4940                 if (val && val->unit == CSSPrimitiveValue::CSS_IDENT) {
4941                     counterName = primitiveValueCache()->createValue(val->string, CSSPrimitiveValue::CSS_STRING);
4942                     state = VAL;
4943                     m_valueList->next();
4944                     continue;
4945                 }
4946                 break;
4947             case VAL: {
4948                 int i = defaultValue;
4949                 if (val && val->unit == CSSPrimitiveValue::CSS_NUMBER) {
4950                     i = clampToInteger(val->fValue);
4951                     m_valueList->next();
4952                 }
4953 
4954                 list->append(primitiveValueCache()->createValue(Pair::create(counterName.release(),
4955                     primitiveValueCache()->createValue(i, CSSPrimitiveValue::CSS_NUMBER))));
4956                 state = ID;
4957                 continue;
4958             }
4959         }
4960         break;
4961     }
4962 
4963     if (list->length() > 0) {
4964         addProperty(propId, list.release(), important);
4965         return true;
4966     }
4967 
4968     return false;
4969 }
4970 
4971 // This should go away once we drop support for -webkit-gradient
parseDeprecatedGradientPoint(CSSParserValue * a,bool horizontal,CSSPrimitiveValueCache * primitiveValueCache)4972 static PassRefPtr<CSSPrimitiveValue> parseDeprecatedGradientPoint(CSSParserValue* a, bool horizontal, CSSPrimitiveValueCache* primitiveValueCache)
4973 {
4974     RefPtr<CSSPrimitiveValue> result;
4975     if (a->unit == CSSPrimitiveValue::CSS_IDENT) {
4976         if ((equalIgnoringCase(a->string, "left") && horizontal) ||
4977             (equalIgnoringCase(a->string, "top") && !horizontal))
4978             result = primitiveValueCache->createValue(0., CSSPrimitiveValue::CSS_PERCENTAGE);
4979         else if ((equalIgnoringCase(a->string, "right") && horizontal) ||
4980                  (equalIgnoringCase(a->string, "bottom") && !horizontal))
4981             result = primitiveValueCache->createValue(100., CSSPrimitiveValue::CSS_PERCENTAGE);
4982         else if (equalIgnoringCase(a->string, "center"))
4983             result = primitiveValueCache->createValue(50., CSSPrimitiveValue::CSS_PERCENTAGE);
4984     } else if (a->unit == CSSPrimitiveValue::CSS_NUMBER || a->unit == CSSPrimitiveValue::CSS_PERCENTAGE)
4985         result = primitiveValueCache->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes)a->unit);
4986     return result;
4987 }
4988 
parseDeprecatedGradientColorStop(CSSParser * p,CSSParserValue * a,CSSGradientColorStop & stop)4989 static bool parseDeprecatedGradientColorStop(CSSParser* p, CSSParserValue* a, CSSGradientColorStop& stop)
4990 {
4991     if (a->unit != CSSParserValue::Function)
4992         return false;
4993 
4994     if (!equalIgnoringCase(a->function->name, "from(") &&
4995         !equalIgnoringCase(a->function->name, "to(") &&
4996         !equalIgnoringCase(a->function->name, "color-stop("))
4997         return false;
4998 
4999     CSSParserValueList* args = a->function->args.get();
5000     if (!args)
5001         return false;
5002 
5003     if (equalIgnoringCase(a->function->name, "from(") ||
5004         equalIgnoringCase(a->function->name, "to(")) {
5005         // The "from" and "to" stops expect 1 argument.
5006         if (args->size() != 1)
5007             return false;
5008 
5009         if (equalIgnoringCase(a->function->name, "from("))
5010             stop.m_position = p->primitiveValueCache()->createValue(0, CSSPrimitiveValue::CSS_NUMBER);
5011         else
5012             stop.m_position = p->primitiveValueCache()->createValue(1, CSSPrimitiveValue::CSS_NUMBER);
5013 
5014         int id = args->current()->id;
5015         if (id == CSSValueWebkitText || (id >= CSSValueAqua && id <= CSSValueWindowtext) || id == CSSValueMenu)
5016             stop.m_color = p->primitiveValueCache()->createIdentifierValue(id);
5017         else
5018             stop.m_color = p->parseColor(args->current());
5019         if (!stop.m_color)
5020             return false;
5021     }
5022 
5023     // The "color-stop" function expects 3 arguments.
5024     if (equalIgnoringCase(a->function->name, "color-stop(")) {
5025         if (args->size() != 3)
5026             return false;
5027 
5028         CSSParserValue* stopArg = args->current();
5029         if (stopArg->unit == CSSPrimitiveValue::CSS_PERCENTAGE)
5030             stop.m_position = p->primitiveValueCache()->createValue(stopArg->fValue / 100, CSSPrimitiveValue::CSS_NUMBER);
5031         else if (stopArg->unit == CSSPrimitiveValue::CSS_NUMBER)
5032             stop.m_position = p->primitiveValueCache()->createValue(stopArg->fValue, CSSPrimitiveValue::CSS_NUMBER);
5033         else
5034             return false;
5035 
5036         stopArg = args->next();
5037         if (stopArg->unit != CSSParserValue::Operator || stopArg->iValue != ',')
5038             return false;
5039 
5040         stopArg = args->next();
5041         int id = stopArg->id;
5042         if (id == CSSValueWebkitText || (id >= CSSValueAqua && id <= CSSValueWindowtext) || id == CSSValueMenu)
5043             stop.m_color = p->primitiveValueCache()->createIdentifierValue(id);
5044         else
5045             stop.m_color = p->parseColor(stopArg);
5046         if (!stop.m_color)
5047             return false;
5048     }
5049 
5050     return true;
5051 }
5052 
parseDeprecatedGradient(RefPtr<CSSValue> & gradient)5053 bool CSSParser::parseDeprecatedGradient(RefPtr<CSSValue>& gradient)
5054 {
5055     // Walk the arguments.
5056     CSSParserValueList* args = m_valueList->current()->function->args.get();
5057     if (!args || args->size() == 0)
5058         return false;
5059 
5060     // The first argument is the gradient type.  It is an identifier.
5061     CSSGradientType gradientType;
5062     CSSParserValue* a = args->current();
5063     if (!a || a->unit != CSSPrimitiveValue::CSS_IDENT)
5064         return false;
5065     if (equalIgnoringCase(a->string, "linear"))
5066         gradientType = CSSLinearGradient;
5067     else if (equalIgnoringCase(a->string, "radial"))
5068         gradientType = CSSRadialGradient;
5069     else
5070         return false;
5071 
5072     RefPtr<CSSGradientValue> result;
5073     switch (gradientType) {
5074         case CSSLinearGradient:
5075             result = CSSLinearGradientValue::create(NonRepeating, true);
5076             break;
5077         case CSSRadialGradient:
5078             result = CSSRadialGradientValue::create(NonRepeating, true);
5079             break;
5080     }
5081 
5082     // Comma.
5083     a = args->next();
5084     if (!a || a->unit != CSSParserValue::Operator || a->iValue != ',')
5085         return false;
5086 
5087     // Next comes the starting point for the gradient as an x y pair.  There is no
5088     // comma between the x and the y values.
5089     // First X.  It can be left, right, number or percent.
5090     a = args->next();
5091     if (!a)
5092         return false;
5093     RefPtr<CSSPrimitiveValue> point = parseDeprecatedGradientPoint(a, true, primitiveValueCache());
5094     if (!point)
5095         return false;
5096     result->setFirstX(point.release());
5097 
5098     // First Y.  It can be top, bottom, number or percent.
5099     a = args->next();
5100     if (!a)
5101         return false;
5102     point = parseDeprecatedGradientPoint(a, false, primitiveValueCache());
5103     if (!point)
5104         return false;
5105     result->setFirstY(point.release());
5106 
5107     // Comma after the first point.
5108     a = args->next();
5109     if (!a || a->unit != CSSParserValue::Operator || a->iValue != ',')
5110         return false;
5111 
5112     // For radial gradients only, we now expect a numeric radius.
5113     if (gradientType == CSSRadialGradient) {
5114         a = args->next();
5115         if (!a || a->unit != CSSPrimitiveValue::CSS_NUMBER)
5116             return false;
5117         static_cast<CSSRadialGradientValue*>(result.get())->setFirstRadius(primitiveValueCache()->createValue(a->fValue, CSSPrimitiveValue::CSS_NUMBER));
5118 
5119         // Comma after the first radius.
5120         a = args->next();
5121         if (!a || a->unit != CSSParserValue::Operator || a->iValue != ',')
5122             return false;
5123     }
5124 
5125     // Next is the ending point for the gradient as an x, y pair.
5126     // Second X.  It can be left, right, number or percent.
5127     a = args->next();
5128     if (!a)
5129         return false;
5130     point = parseDeprecatedGradientPoint(a, true, primitiveValueCache());
5131     if (!point)
5132         return false;
5133     result->setSecondX(point.release());
5134 
5135     // Second Y.  It can be top, bottom, number or percent.
5136     a = args->next();
5137     if (!a)
5138         return false;
5139     point = parseDeprecatedGradientPoint(a, false, primitiveValueCache());
5140     if (!point)
5141         return false;
5142     result->setSecondY(point.release());
5143 
5144     // For radial gradients only, we now expect the second radius.
5145     if (gradientType == CSSRadialGradient) {
5146         // Comma after the second point.
5147         a = args->next();
5148         if (!a || a->unit != CSSParserValue::Operator || a->iValue != ',')
5149             return false;
5150 
5151         a = args->next();
5152         if (!a || a->unit != CSSPrimitiveValue::CSS_NUMBER)
5153             return false;
5154         static_cast<CSSRadialGradientValue*>(result.get())->setSecondRadius(primitiveValueCache()->createValue(a->fValue, CSSPrimitiveValue::CSS_NUMBER));
5155     }
5156 
5157     // We now will accept any number of stops (0 or more).
5158     a = args->next();
5159     while (a) {
5160         // Look for the comma before the next stop.
5161         if (a->unit != CSSParserValue::Operator || a->iValue != ',')
5162             return false;
5163 
5164         // Now examine the stop itself.
5165         a = args->next();
5166         if (!a)
5167             return false;
5168 
5169         // The function name needs to be one of "from", "to", or "color-stop."
5170         CSSGradientColorStop stop;
5171         if (!parseDeprecatedGradientColorStop(this, a, stop))
5172             return false;
5173         result->addStop(stop);
5174 
5175         // Advance
5176         a = args->next();
5177     }
5178 
5179     gradient = result.release();
5180     return true;
5181 }
5182 
valueFromSideKeyword(CSSParserValue * a,bool & isHorizontal,CSSPrimitiveValueCache * primitiveValueCache)5183 static PassRefPtr<CSSPrimitiveValue> valueFromSideKeyword(CSSParserValue* a, bool& isHorizontal, CSSPrimitiveValueCache* primitiveValueCache)
5184 {
5185     if (a->unit != CSSPrimitiveValue::CSS_IDENT)
5186         return 0;
5187 
5188     switch (a->id) {
5189         case CSSValueLeft:
5190         case CSSValueRight:
5191             isHorizontal = true;
5192             break;
5193         case CSSValueTop:
5194         case CSSValueBottom:
5195             isHorizontal = false;
5196             break;
5197         default:
5198             return 0;
5199     }
5200     return primitiveValueCache->createIdentifierValue(a->id);
5201 }
5202 
parseGradientColorOrKeyword(CSSParser * p,CSSParserValue * value)5203 static PassRefPtr<CSSPrimitiveValue> parseGradientColorOrKeyword(CSSParser* p, CSSParserValue* value)
5204 {
5205     int id = value->id;
5206     if (id == CSSValueWebkitText || (id >= CSSValueAqua && id <= CSSValueWindowtext) || id == CSSValueMenu)
5207         return p->primitiveValueCache()->createIdentifierValue(id);
5208 
5209     return p->parseColor(value);
5210 }
5211 
parseLinearGradient(RefPtr<CSSValue> & gradient,CSSGradientRepeat repeating)5212 bool CSSParser::parseLinearGradient(RefPtr<CSSValue>& gradient, CSSGradientRepeat repeating)
5213 {
5214     RefPtr<CSSLinearGradientValue> result = CSSLinearGradientValue::create(repeating);
5215 
5216     // Walk the arguments.
5217     CSSParserValueList* args = m_valueList->current()->function->args.get();
5218     if (!args || !args->size())
5219         return false;
5220 
5221     CSSParserValue* a = args->current();
5222     if (!a)
5223         return false;
5224 
5225     bool expectComma = false;
5226     // Look for angle.
5227     if (validUnit(a, FAngle, true)) {
5228         result->setAngle(primitiveValueCache()->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes)a->unit));
5229 
5230         a = args->next();
5231         expectComma = true;
5232     } else {
5233         // Look one or two optional keywords that indicate a side or corner.
5234         RefPtr<CSSPrimitiveValue> startX, startY;
5235 
5236         RefPtr<CSSPrimitiveValue> location;
5237         bool isHorizontal = false;
5238         if ((location = valueFromSideKeyword(a, isHorizontal, primitiveValueCache()))) {
5239             if (isHorizontal)
5240                 startX = location;
5241             else
5242                 startY = location;
5243 
5244             a = args->next();
5245             if (a) {
5246                 if ((location = valueFromSideKeyword(a, isHorizontal, primitiveValueCache()))) {
5247                     if (isHorizontal) {
5248                         if (startX)
5249                             return false;
5250                         startX = location;
5251                     } else {
5252                         if (startY)
5253                             return false;
5254                         startY = location;
5255                     }
5256 
5257                     a = args->next();
5258                 }
5259             }
5260 
5261             expectComma = true;
5262         }
5263 
5264         if (!startX && !startY)
5265             startY = primitiveValueCache()->createIdentifierValue(CSSValueTop);
5266 
5267         result->setFirstX(startX.release());
5268         result->setFirstY(startY.release());
5269     }
5270 
5271     if (!parseGradientColorStops(args, result.get(), expectComma))
5272         return false;
5273 
5274     Vector<CSSGradientColorStop>& stops = result->stops();
5275     if (stops.isEmpty())
5276         return false;
5277 
5278     gradient = result.release();
5279     return true;
5280 }
5281 
parseRadialGradient(RefPtr<CSSValue> & gradient,CSSGradientRepeat repeating)5282 bool CSSParser::parseRadialGradient(RefPtr<CSSValue>& gradient, CSSGradientRepeat repeating)
5283 {
5284     RefPtr<CSSRadialGradientValue> result = CSSRadialGradientValue::create(repeating);
5285 
5286     // Walk the arguments.
5287     CSSParserValueList* args = m_valueList->current()->function->args.get();
5288     if (!args || !args->size())
5289         return false;
5290 
5291     CSSParserValue* a = args->current();
5292     if (!a)
5293         return false;
5294 
5295     bool expectComma = false;
5296 
5297     // Optional background-position
5298     RefPtr<CSSValue> centerX;
5299     RefPtr<CSSValue> centerY;
5300     // parseFillPosition advances the args next pointer.
5301     parseFillPosition(args, centerX, centerY);
5302     a = args->current();
5303 
5304     if (centerX || centerY) {
5305         // Comma
5306         if (a->unit != CSSParserValue::Operator || a->iValue != ',')
5307             return false;
5308 
5309         a = args->next();
5310         if (!a)
5311             return false;
5312     }
5313 
5314     ASSERT(!centerX || centerX->isPrimitiveValue());
5315     ASSERT(!centerY || centerY->isPrimitiveValue());
5316 
5317     result->setFirstX(static_cast<CSSPrimitiveValue*>(centerX.get()));
5318     result->setSecondX(static_cast<CSSPrimitiveValue*>(centerX.get()));
5319     // CSS3 radial gradients always share the same start and end point.
5320     result->setFirstY(static_cast<CSSPrimitiveValue*>(centerY.get()));
5321     result->setSecondY(static_cast<CSSPrimitiveValue*>(centerY.get()));
5322 
5323     RefPtr<CSSPrimitiveValue> shapeValue;
5324     RefPtr<CSSPrimitiveValue> sizeValue;
5325 
5326     // Optional shape and/or size in any order.
5327     for (int i = 0; i < 2; ++i) {
5328         if (a->unit != CSSPrimitiveValue::CSS_IDENT)
5329             break;
5330 
5331         bool foundValue = false;
5332         switch (a->id) {
5333         case CSSValueCircle:
5334         case CSSValueEllipse:
5335             shapeValue = primitiveValueCache()->createIdentifierValue(a->id);
5336             foundValue = true;
5337             break;
5338         case CSSValueClosestSide:
5339         case CSSValueClosestCorner:
5340         case CSSValueFarthestSide:
5341         case CSSValueFarthestCorner:
5342         case CSSValueContain:
5343         case CSSValueCover:
5344             sizeValue = primitiveValueCache()->createIdentifierValue(a->id);
5345             foundValue = true;
5346             break;
5347         }
5348 
5349         if (foundValue) {
5350             a = args->next();
5351             if (!a)
5352                 return false;
5353 
5354             expectComma = true;
5355         }
5356     }
5357 
5358     result->setShape(shapeValue);
5359     result->setSizingBehavior(sizeValue);
5360 
5361     // Or, two lengths or percentages
5362     RefPtr<CSSPrimitiveValue> horizontalSize;
5363     RefPtr<CSSPrimitiveValue> verticalSize;
5364 
5365     if (!shapeValue && !sizeValue) {
5366         if (validUnit(a, FLength | FPercent, m_strict)) {
5367             horizontalSize = primitiveValueCache()->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes) a->unit);
5368             a = args->next();
5369             if (!a)
5370                 return false;
5371 
5372             expectComma = true;
5373         }
5374 
5375         if (validUnit(a, FLength | FPercent, m_strict)) {
5376             verticalSize = primitiveValueCache()->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes) a->unit);
5377 
5378             a = args->next();
5379             if (!a)
5380                 return false;
5381             expectComma = true;
5382         }
5383     }
5384 
5385     // Must have neither or both.
5386     if (!horizontalSize != !verticalSize)
5387         return false;
5388 
5389     result->setEndHorizontalSize(horizontalSize);
5390     result->setEndVerticalSize(verticalSize);
5391 
5392     if (!parseGradientColorStops(args, result.get(), expectComma))
5393         return false;
5394 
5395     gradient = result.release();
5396     return true;
5397 }
5398 
parseGradientColorStops(CSSParserValueList * valueList,CSSGradientValue * gradient,bool expectComma)5399 bool CSSParser::parseGradientColorStops(CSSParserValueList* valueList, CSSGradientValue* gradient, bool expectComma)
5400 {
5401     CSSParserValue* a = valueList->current();
5402 
5403     // Now look for color stops.
5404     while (a) {
5405         // Look for the comma before the next stop.
5406         if (expectComma) {
5407             if (a->unit != CSSParserValue::Operator || a->iValue != ',')
5408                 return false;
5409 
5410             a = valueList->next();
5411             if (!a)
5412                 return false;
5413         }
5414 
5415         // <color-stop> = <color> [ <percentage> | <length> ]?
5416         CSSGradientColorStop stop;
5417         stop.m_color = parseGradientColorOrKeyword(this, a);
5418         if (!stop.m_color)
5419             return false;
5420 
5421         a = valueList->next();
5422         if (a) {
5423             if (validUnit(a, FLength | FPercent, m_strict)) {
5424                 stop.m_position = primitiveValueCache()->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes)a->unit);
5425                 a = valueList->next();
5426             }
5427         }
5428 
5429         gradient->addStop(stop);
5430         expectComma = true;
5431     }
5432 
5433     // Must have 2 or more stops to be valid.
5434     return gradient->stops().size() > 1;
5435 }
5436 
isGeneratedImageValue(CSSParserValue * val) const5437 bool CSSParser::isGeneratedImageValue(CSSParserValue* val) const
5438 {
5439     if (val->unit != CSSParserValue::Function)
5440         return false;
5441 
5442     return equalIgnoringCase(val->function->name, "-webkit-gradient(")
5443         || equalIgnoringCase(val->function->name, "-webkit-linear-gradient(")
5444         || equalIgnoringCase(val->function->name, "-webkit-repeating-linear-gradient(")
5445         || equalIgnoringCase(val->function->name, "-webkit-radial-gradient(")
5446         || equalIgnoringCase(val->function->name, "-webkit-repeating-radial-gradient(")
5447         || equalIgnoringCase(val->function->name, "-webkit-canvas(");
5448 }
5449 
parseGeneratedImage(RefPtr<CSSValue> & value)5450 bool CSSParser::parseGeneratedImage(RefPtr<CSSValue>& value)
5451 {
5452     CSSParserValue* val = m_valueList->current();
5453 
5454     if (val->unit != CSSParserValue::Function)
5455         return false;
5456 
5457     if (equalIgnoringCase(val->function->name, "-webkit-gradient("))
5458         return parseDeprecatedGradient(value);
5459 
5460     if (equalIgnoringCase(val->function->name, "-webkit-linear-gradient("))
5461         return parseLinearGradient(value, NonRepeating);
5462 
5463     if (equalIgnoringCase(val->function->name, "-webkit-repeating-linear-gradient("))
5464         return parseLinearGradient(value, Repeating);
5465 
5466     if (equalIgnoringCase(val->function->name, "-webkit-radial-gradient("))
5467         return parseRadialGradient(value, NonRepeating);
5468 
5469     if (equalIgnoringCase(val->function->name, "-webkit-repeating-radial-gradient("))
5470         return parseRadialGradient(value, Repeating);
5471 
5472     if (equalIgnoringCase(val->function->name, "-webkit-canvas("))
5473         return parseCanvas(value);
5474 
5475     return false;
5476 }
5477 
parseCanvas(RefPtr<CSSValue> & canvas)5478 bool CSSParser::parseCanvas(RefPtr<CSSValue>& canvas)
5479 {
5480     RefPtr<CSSCanvasValue> result = CSSCanvasValue::create();
5481 
5482     // Walk the arguments.
5483     CSSParserValueList* args = m_valueList->current()->function->args.get();
5484     if (!args || args->size() != 1)
5485         return false;
5486 
5487     // The first argument is the canvas name.  It is an identifier.
5488     CSSParserValue* a = args->current();
5489     if (!a || a->unit != CSSPrimitiveValue::CSS_IDENT)
5490         return false;
5491     result->setName(a->string);
5492     canvas = result;
5493     return true;
5494 }
5495 
5496 class TransformOperationInfo {
5497 public:
TransformOperationInfo(const CSSParserString & name)5498     TransformOperationInfo(const CSSParserString& name)
5499     : m_type(WebKitCSSTransformValue::UnknownTransformOperation)
5500     , m_argCount(1)
5501     , m_allowSingleArgument(false)
5502     , m_unit(CSSParser::FUnknown)
5503     {
5504         if (equalIgnoringCase(name, "scale(") || equalIgnoringCase(name, "scalex(") || equalIgnoringCase(name, "scaley(") || equalIgnoringCase(name, "scalez(")) {
5505             m_unit = CSSParser::FNumber;
5506             if (equalIgnoringCase(name, "scale("))
5507                 m_type = WebKitCSSTransformValue::ScaleTransformOperation;
5508             else if (equalIgnoringCase(name, "scalex("))
5509                 m_type = WebKitCSSTransformValue::ScaleXTransformOperation;
5510             else if (equalIgnoringCase(name, "scaley("))
5511                 m_type = WebKitCSSTransformValue::ScaleYTransformOperation;
5512             else
5513                 m_type = WebKitCSSTransformValue::ScaleZTransformOperation;
5514         } else if (equalIgnoringCase(name, "scale3d(")) {
5515             m_type = WebKitCSSTransformValue::Scale3DTransformOperation;
5516             m_argCount = 5;
5517             m_unit = CSSParser::FNumber;
5518         } else if (equalIgnoringCase(name, "rotate(")) {
5519             m_type = WebKitCSSTransformValue::RotateTransformOperation;
5520             m_unit = CSSParser::FAngle;
5521         } else if (equalIgnoringCase(name, "rotatex(") ||
5522                    equalIgnoringCase(name, "rotatey(") ||
5523                    equalIgnoringCase(name, "rotatez(")) {
5524             m_unit = CSSParser::FAngle;
5525             if (equalIgnoringCase(name, "rotatex("))
5526                 m_type = WebKitCSSTransformValue::RotateXTransformOperation;
5527             else if (equalIgnoringCase(name, "rotatey("))
5528                 m_type = WebKitCSSTransformValue::RotateYTransformOperation;
5529             else
5530                 m_type = WebKitCSSTransformValue::RotateZTransformOperation;
5531         } else if (equalIgnoringCase(name, "rotate3d(")) {
5532             m_type = WebKitCSSTransformValue::Rotate3DTransformOperation;
5533             m_argCount = 7;
5534             m_unit = CSSParser::FNumber;
5535         } else if (equalIgnoringCase(name, "skew(") || equalIgnoringCase(name, "skewx(") || equalIgnoringCase(name, "skewy(")) {
5536             m_unit = CSSParser::FAngle;
5537             if (equalIgnoringCase(name, "skew("))
5538                 m_type = WebKitCSSTransformValue::SkewTransformOperation;
5539             else if (equalIgnoringCase(name, "skewx("))
5540                 m_type = WebKitCSSTransformValue::SkewXTransformOperation;
5541             else
5542                 m_type = WebKitCSSTransformValue::SkewYTransformOperation;
5543         } else if (equalIgnoringCase(name, "translate(") || equalIgnoringCase(name, "translatex(") || equalIgnoringCase(name, "translatey(") || equalIgnoringCase(name, "translatez(")) {
5544             m_unit = CSSParser::FLength | CSSParser::FPercent;
5545             if (equalIgnoringCase(name, "translate("))
5546                 m_type = WebKitCSSTransformValue::TranslateTransformOperation;
5547             else if (equalIgnoringCase(name, "translatex("))
5548                 m_type = WebKitCSSTransformValue::TranslateXTransformOperation;
5549             else if (equalIgnoringCase(name, "translatey("))
5550                 m_type = WebKitCSSTransformValue::TranslateYTransformOperation;
5551             else
5552                 m_type = WebKitCSSTransformValue::TranslateZTransformOperation;
5553         } else if (equalIgnoringCase(name, "translate3d(")) {
5554             m_type = WebKitCSSTransformValue::Translate3DTransformOperation;
5555             m_argCount = 5;
5556             m_unit = CSSParser::FLength | CSSParser::FPercent;
5557         } else if (equalIgnoringCase(name, "matrix(")) {
5558             m_type = WebKitCSSTransformValue::MatrixTransformOperation;
5559             m_argCount = 11;
5560             m_unit = CSSParser::FNumber;
5561         } else if (equalIgnoringCase(name, "matrix3d(")) {
5562             m_type = WebKitCSSTransformValue::Matrix3DTransformOperation;
5563             m_argCount = 31;
5564             m_unit = CSSParser::FNumber;
5565         } else if (equalIgnoringCase(name, "perspective(")) {
5566             m_type = WebKitCSSTransformValue::PerspectiveTransformOperation;
5567             m_unit = CSSParser::FNumber;
5568         }
5569 
5570         if (equalIgnoringCase(name, "scale(") || equalIgnoringCase(name, "skew(") || equalIgnoringCase(name, "translate(")) {
5571             m_allowSingleArgument = true;
5572             m_argCount = 3;
5573         }
5574     }
5575 
type() const5576     WebKitCSSTransformValue::TransformOperationType type() const { return m_type; }
argCount() const5577     unsigned argCount() const { return m_argCount; }
unit() const5578     CSSParser::Units unit() const { return m_unit; }
5579 
unknown() const5580     bool unknown() const { return m_type == WebKitCSSTransformValue::UnknownTransformOperation; }
hasCorrectArgCount(unsigned argCount)5581     bool hasCorrectArgCount(unsigned argCount) { return m_argCount == argCount || (m_allowSingleArgument && argCount == 1); }
5582 
5583 private:
5584     WebKitCSSTransformValue::TransformOperationType m_type;
5585     unsigned m_argCount;
5586     bool m_allowSingleArgument;
5587     CSSParser::Units m_unit;
5588 };
5589 
parseTransform()5590 PassRefPtr<CSSValueList> CSSParser::parseTransform()
5591 {
5592     if (!m_valueList)
5593         return 0;
5594 
5595     // The transform is a list of functional primitives that specify transform operations.
5596     // We collect a list of WebKitCSSTransformValues, where each value specifies a single operation.
5597     RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
5598     for (CSSParserValue* value = m_valueList->current(); value; value = m_valueList->next()) {
5599         if (value->unit != CSSParserValue::Function || !value->function)
5600             return 0;
5601 
5602         // Every primitive requires at least one argument.
5603         CSSParserValueList* args = value->function->args.get();
5604         if (!args)
5605             return 0;
5606 
5607         // See if the specified primitive is one we understand.
5608         TransformOperationInfo info(value->function->name);
5609         if (info.unknown())
5610             return 0;
5611 
5612         if (!info.hasCorrectArgCount(args->size()))
5613             return 0;
5614 
5615         // Create the new WebKitCSSTransformValue for this operation and add it to our list.
5616         RefPtr<WebKitCSSTransformValue> transformValue = WebKitCSSTransformValue::create(info.type());
5617         list->append(transformValue);
5618 
5619         // Snag our values.
5620         CSSParserValue* a = args->current();
5621         unsigned argNumber = 0;
5622         while (a) {
5623             CSSParser::Units unit = info.unit();
5624 
5625             if (info.type() == WebKitCSSTransformValue::Rotate3DTransformOperation && argNumber == 3) {
5626                 // 4th param of rotate3d() is an angle rather than a bare number, validate it as such
5627                 if (!validUnit(a, FAngle, true))
5628                     return 0;
5629             } else if (info.type() == WebKitCSSTransformValue::Translate3DTransformOperation && argNumber == 2) {
5630                 // 3rd param of translate3d() cannot be a percentage
5631                 if (!validUnit(a, FLength, true))
5632                     return 0;
5633             } else if (info.type() == WebKitCSSTransformValue::TranslateZTransformOperation && argNumber == 0) {
5634                 // 1st param of translateZ() cannot be a percentage
5635                 if (!validUnit(a, FLength, true))
5636                     return 0;
5637             } else if (info.type() == WebKitCSSTransformValue::PerspectiveTransformOperation && argNumber == 0) {
5638                 // 1st param of perspective() must be a non-negative number (deprecated) or length.
5639                 if (!validUnit(a, FNumber | FLength | FNonNeg, true))
5640                     return 0;
5641             } else if (!validUnit(a, unit, true))
5642                 return 0;
5643 
5644             // Add the value to the current transform operation.
5645             transformValue->append(primitiveValueCache()->createValue(a->fValue, (CSSPrimitiveValue::UnitTypes) a->unit));
5646 
5647             a = args->next();
5648             if (!a)
5649                 break;
5650             if (a->unit != CSSParserValue::Operator || a->iValue != ',')
5651                 return 0;
5652             a = args->next();
5653 
5654             argNumber++;
5655         }
5656     }
5657 
5658     return list.release();
5659 }
5660 
parseTransformOrigin(int propId,int & propId1,int & propId2,int & propId3,RefPtr<CSSValue> & value,RefPtr<CSSValue> & value2,RefPtr<CSSValue> & value3)5661 bool CSSParser::parseTransformOrigin(int propId, int& propId1, int& propId2, int& propId3, RefPtr<CSSValue>& value, RefPtr<CSSValue>& value2, RefPtr<CSSValue>& value3)
5662 {
5663     propId1 = propId;
5664     propId2 = propId;
5665     propId3 = propId;
5666     if (propId == CSSPropertyWebkitTransformOrigin) {
5667         propId1 = CSSPropertyWebkitTransformOriginX;
5668         propId2 = CSSPropertyWebkitTransformOriginY;
5669         propId3 = CSSPropertyWebkitTransformOriginZ;
5670     }
5671 
5672     switch (propId) {
5673         case CSSPropertyWebkitTransformOrigin:
5674             if (!parseTransformOriginShorthand(value, value2, value3))
5675                 return false;
5676             // parseTransformOriginShorthand advances the m_valueList pointer
5677             break;
5678         case CSSPropertyWebkitTransformOriginX: {
5679             value = parseFillPositionX(m_valueList);
5680             if (value)
5681                 m_valueList->next();
5682             break;
5683         }
5684         case CSSPropertyWebkitTransformOriginY: {
5685             value = parseFillPositionY(m_valueList);
5686             if (value)
5687                 m_valueList->next();
5688             break;
5689         }
5690         case CSSPropertyWebkitTransformOriginZ: {
5691             if (validUnit(m_valueList->current(), FLength, m_strict))
5692                 value = primitiveValueCache()->createValue(m_valueList->current()->fValue, (CSSPrimitiveValue::UnitTypes)m_valueList->current()->unit);
5693             if (value)
5694                 m_valueList->next();
5695             break;
5696         }
5697     }
5698 
5699     return value;
5700 }
5701 
parsePerspectiveOrigin(int propId,int & propId1,int & propId2,RefPtr<CSSValue> & value,RefPtr<CSSValue> & value2)5702 bool CSSParser::parsePerspectiveOrigin(int propId, int& propId1, int& propId2, RefPtr<CSSValue>& value, RefPtr<CSSValue>& value2)
5703 {
5704     propId1 = propId;
5705     propId2 = propId;
5706     if (propId == CSSPropertyWebkitPerspectiveOrigin) {
5707         propId1 = CSSPropertyWebkitPerspectiveOriginX;
5708         propId2 = CSSPropertyWebkitPerspectiveOriginY;
5709     }
5710 
5711     switch (propId) {
5712         case CSSPropertyWebkitPerspectiveOrigin:
5713             parseFillPosition(m_valueList, value, value2);
5714             break;
5715         case CSSPropertyWebkitPerspectiveOriginX: {
5716             value = parseFillPositionX(m_valueList);
5717             if (value)
5718                 m_valueList->next();
5719             break;
5720         }
5721         case CSSPropertyWebkitPerspectiveOriginY: {
5722             value = parseFillPositionY(m_valueList);
5723             if (value)
5724                 m_valueList->next();
5725             break;
5726         }
5727     }
5728 
5729     return value;
5730 }
5731 
parseTextEmphasisStyle(bool important)5732 bool CSSParser::parseTextEmphasisStyle(bool important)
5733 {
5734     unsigned valueListSize = m_valueList->size();
5735 
5736     RefPtr<CSSPrimitiveValue> fill;
5737     RefPtr<CSSPrimitiveValue> shape;
5738 
5739     for (CSSParserValue* value = m_valueList->current(); value; value = m_valueList->next()) {
5740         if (value->unit == CSSPrimitiveValue::CSS_STRING) {
5741             if (fill || shape || (valueListSize != 1 && !inShorthand()))
5742                 return false;
5743             addProperty(CSSPropertyWebkitTextEmphasisStyle, primitiveValueCache()->createValue(value->string, CSSPrimitiveValue::CSS_STRING), important);
5744             m_valueList->next();
5745             return true;
5746         }
5747 
5748         if (value->id == CSSValueNone) {
5749             if (fill || shape || (valueListSize != 1 && !inShorthand()))
5750                 return false;
5751             addProperty(CSSPropertyWebkitTextEmphasisStyle, primitiveValueCache()->createIdentifierValue(CSSValueNone), important);
5752             m_valueList->next();
5753             return true;
5754         }
5755 
5756         if (value->id == CSSValueOpen || value->id == CSSValueFilled) {
5757             if (fill)
5758                 return false;
5759             fill = primitiveValueCache()->createIdentifierValue(value->id);
5760         } else if (value->id == CSSValueDot || value->id == CSSValueCircle || value->id == CSSValueDoubleCircle || value->id == CSSValueTriangle || value->id == CSSValueSesame) {
5761             if (shape)
5762                 return false;
5763             shape = primitiveValueCache()->createIdentifierValue(value->id);
5764         } else if (!inShorthand())
5765             return false;
5766         else
5767             break;
5768     }
5769 
5770     if (fill && shape) {
5771         RefPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated();
5772         parsedValues->append(fill.release());
5773         parsedValues->append(shape.release());
5774         addProperty(CSSPropertyWebkitTextEmphasisStyle, parsedValues.release(), important);
5775         return true;
5776     }
5777     if (fill) {
5778         addProperty(CSSPropertyWebkitTextEmphasisStyle, fill.release(), important);
5779         return true;
5780     }
5781     if (shape) {
5782         addProperty(CSSPropertyWebkitTextEmphasisStyle, shape.release(), important);
5783         return true;
5784     }
5785 
5786     return false;
5787 }
5788 
parseLineBoxContain(bool important)5789 bool CSSParser::parseLineBoxContain(bool important)
5790 {
5791     LineBoxContain lineBoxContain = LineBoxContainNone;
5792 
5793     for (CSSParserValue* value = m_valueList->current(); value; value = m_valueList->next()) {
5794         if (value->id == CSSValueBlock) {
5795             if (lineBoxContain & LineBoxContainBlock)
5796                 return false;
5797             lineBoxContain |= LineBoxContainBlock;
5798         } else if (value->id == CSSValueInline) {
5799             if (lineBoxContain & LineBoxContainInline)
5800                 return false;
5801             lineBoxContain |= LineBoxContainInline;
5802         } else if (value->id == CSSValueFont) {
5803             if (lineBoxContain & LineBoxContainFont)
5804                 return false;
5805             lineBoxContain |= LineBoxContainFont;
5806         } else if (value->id == CSSValueGlyphs) {
5807             if (lineBoxContain & LineBoxContainGlyphs)
5808                 return false;
5809             lineBoxContain |= LineBoxContainGlyphs;
5810         } else if (value->id == CSSValueReplaced) {
5811             if (lineBoxContain & LineBoxContainReplaced)
5812                 return false;
5813             lineBoxContain |= LineBoxContainReplaced;
5814         } else if (value->id == CSSValueInlineBox) {
5815             if (lineBoxContain & LineBoxContainInlineBox)
5816                 return false;
5817             lineBoxContain |= LineBoxContainInlineBox;
5818         } else
5819             return false;
5820     }
5821 
5822     if (!lineBoxContain)
5823         return false;
5824 
5825     addProperty(CSSPropertyWebkitLineBoxContain, CSSLineBoxContainValue::create(lineBoxContain), important);
5826     return true;
5827 }
5828 
yyerror(const char *)5829 static inline int yyerror(const char*) { return 1; }
5830 
5831 #define END_TOKEN 0
5832 
5833 #include "CSSGrammar.h"
5834 
lex(void * yylvalWithoutType)5835 int CSSParser::lex(void* yylvalWithoutType)
5836 {
5837     YYSTYPE* yylval = static_cast<YYSTYPE*>(yylvalWithoutType);
5838     int length;
5839 
5840     lex();
5841 
5842     UChar* t = text(&length);
5843 
5844     switch (token()) {
5845     case WHITESPACE:
5846     case SGML_CD:
5847     case INCLUDES:
5848     case DASHMATCH:
5849         break;
5850 
5851     case URI:
5852     case STRING:
5853     case IDENT:
5854     case NTH:
5855     case HEX:
5856     case IDSEL:
5857     case DIMEN:
5858     case UNICODERANGE:
5859     case FUNCTION:
5860     case ANYFUNCTION:
5861     case NOTFUNCTION:
5862     case CALCFUNCTION:
5863     case MINFUNCTION:
5864     case MAXFUNCTION:
5865         yylval->string.characters = t;
5866         yylval->string.length = length;
5867         break;
5868 
5869     case IMPORT_SYM:
5870     case PAGE_SYM:
5871     case MEDIA_SYM:
5872     case FONT_FACE_SYM:
5873     case CHARSET_SYM:
5874     case NAMESPACE_SYM:
5875     case WEBKIT_KEYFRAMES_SYM:
5876 
5877     case IMPORTANT_SYM:
5878         break;
5879 
5880     case QEMS:
5881         length--;
5882     case GRADS:
5883     case TURNS:
5884         length--;
5885     case DEGS:
5886     case RADS:
5887     case KHERTZ:
5888     case REMS:
5889         length--;
5890     case MSECS:
5891     case HERTZ:
5892     case EMS:
5893     case EXS:
5894     case PXS:
5895     case CMS:
5896     case MMS:
5897     case INS:
5898     case PTS:
5899     case PCS:
5900         length--;
5901     case SECS:
5902     case PERCENTAGE:
5903         length--;
5904     case FLOATTOKEN:
5905     case INTEGER:
5906         yylval->number = charactersToDouble(t, length);
5907         break;
5908 
5909     default:
5910         break;
5911     }
5912 
5913     return token();
5914 }
5915 
recheckAtKeyword(const UChar * str,int len)5916 void CSSParser::recheckAtKeyword(const UChar* str, int len)
5917 {
5918     String ruleName(str, len);
5919     if (equalIgnoringCase(ruleName, "@import"))
5920         yyTok = IMPORT_SYM;
5921     else if (equalIgnoringCase(ruleName, "@page"))
5922         yyTok = PAGE_SYM;
5923     else if (equalIgnoringCase(ruleName, "@media"))
5924         yyTok = MEDIA_SYM;
5925     else if (equalIgnoringCase(ruleName, "@font-face"))
5926         yyTok = FONT_FACE_SYM;
5927     else if (equalIgnoringCase(ruleName, "@charset"))
5928         yyTok = CHARSET_SYM;
5929     else if (equalIgnoringCase(ruleName, "@namespace"))
5930         yyTok = NAMESPACE_SYM;
5931     else if (equalIgnoringCase(ruleName, "@-webkit-keyframes"))
5932         yyTok = WEBKIT_KEYFRAMES_SYM;
5933     else if (equalIgnoringCase(ruleName, "@-webkit-mediaquery"))
5934         yyTok = WEBKIT_MEDIAQUERY_SYM;
5935 }
5936 
text(int * length)5937 UChar* CSSParser::text(int *length)
5938 {
5939     UChar* start = yytext;
5940     int l = yyleng;
5941     switch (yyTok) {
5942     case STRING:
5943         l--;
5944         /* nobreak */
5945     case HEX:
5946     case IDSEL:
5947         start++;
5948         l--;
5949         break;
5950     case URI:
5951         // "url("{w}{string}{w}")"
5952         // "url("{w}{url}{w}")"
5953         // strip "url(" and ")"
5954         start += 4;
5955         l -= 5;
5956         // strip {w}
5957         while (l && isHTMLSpace(*start)) {
5958             ++start;
5959             --l;
5960         }
5961         while (l && isHTMLSpace(start[l - 1]))
5962             --l;
5963         if (l && (*start == '"' || *start == '\'')) {
5964             ASSERT(l >= 2 && start[l - 1] == *start);
5965             ++start;
5966             l -= 2;
5967         }
5968         break;
5969     default:
5970         break;
5971     }
5972 
5973     // process escapes
5974     UChar* out = start;
5975     UChar* escape = 0;
5976 
5977     bool sawEscape = false;
5978 
5979     for (int i = 0; i < l; i++) {
5980         UChar* current = start + i;
5981         if (escape == current - 1) {
5982             if (isASCIIHexDigit(*current))
5983                 continue;
5984             if (yyTok == STRING &&
5985                  (*current == '\n' || *current == '\r' || *current == '\f')) {
5986                 // ### handle \r\n case
5987                 if (*current != '\r')
5988                     escape = 0;
5989                 continue;
5990             }
5991             // in all other cases copy the char to output
5992             // ###
5993             *out++ = *current;
5994             escape = 0;
5995             continue;
5996         }
5997         if (escape == current - 2 && yyTok == STRING &&
5998              *(current-1) == '\r' && *current == '\n') {
5999             escape = 0;
6000             continue;
6001         }
6002         if (escape > current - 7 && isASCIIHexDigit(*current))
6003             continue;
6004         if (escape) {
6005             // add escaped char
6006             unsigned uc = 0;
6007             escape++;
6008             while (escape < current) {
6009                 uc *= 16;
6010                 uc += toASCIIHexValue(*escape);
6011                 escape++;
6012             }
6013             // can't handle chars outside ucs2
6014             if (uc > 0xffff)
6015                 uc = 0xfffd;
6016             *out++ = uc;
6017             escape = 0;
6018             if (isHTMLSpace(*current))
6019                 continue;
6020         }
6021         if (!escape && *current == '\\') {
6022             escape = current;
6023             sawEscape = true;
6024             continue;
6025         }
6026         *out++ = *current;
6027     }
6028     if (escape) {
6029         // add escaped char
6030         unsigned uc = 0;
6031         escape++;
6032         while (escape < start+l) {
6033             uc *= 16;
6034             uc += toASCIIHexValue(*escape);
6035             escape++;
6036         }
6037         // can't handle chars outside ucs2
6038         if (uc > 0xffff)
6039             uc = 0xfffd;
6040         *out++ = uc;
6041     }
6042 
6043     *length = out - start;
6044 
6045     // If we have an unrecognized @-keyword, and if we handled any escapes at all, then
6046     // we should attempt to adjust yyTok to the correct type.
6047     if (yyTok == ATKEYWORD && sawEscape)
6048         recheckAtKeyword(start, *length);
6049 
6050     return start;
6051 }
6052 
countLines()6053 void CSSParser::countLines()
6054 {
6055     for (UChar* current = yytext; current < yytext + yyleng; ++current) {
6056         if (*current == '\n')
6057             ++m_lineNumber;
6058     }
6059 }
6060 
createFloatingSelector()6061 CSSParserSelector* CSSParser::createFloatingSelector()
6062 {
6063     CSSParserSelector* selector = new CSSParserSelector;
6064     m_floatingSelectors.add(selector);
6065     return selector;
6066 }
6067 
sinkFloatingSelector(CSSParserSelector * selector)6068 PassOwnPtr<CSSParserSelector> CSSParser::sinkFloatingSelector(CSSParserSelector* selector)
6069 {
6070     if (selector) {
6071         ASSERT(m_floatingSelectors.contains(selector));
6072         m_floatingSelectors.remove(selector);
6073     }
6074     return adoptPtr(selector);
6075 }
6076 
createFloatingSelectorVector()6077 Vector<OwnPtr<CSSParserSelector> >* CSSParser::createFloatingSelectorVector()
6078 {
6079     Vector<OwnPtr<CSSParserSelector> >* selectorVector = new Vector<OwnPtr<CSSParserSelector> >;
6080     m_floatingSelectorVectors.add(selectorVector);
6081     return selectorVector;
6082 }
6083 
sinkFloatingSelectorVector(Vector<OwnPtr<CSSParserSelector>> * selectorVector)6084 PassOwnPtr<Vector<OwnPtr<CSSParserSelector> > > CSSParser::sinkFloatingSelectorVector(Vector<OwnPtr<CSSParserSelector> >* selectorVector)
6085 {
6086     if (selectorVector) {
6087         ASSERT(m_floatingSelectorVectors.contains(selectorVector));
6088         m_floatingSelectorVectors.remove(selectorVector);
6089     }
6090     return adoptPtr(selectorVector);
6091 }
6092 
createFloatingValueList()6093 CSSParserValueList* CSSParser::createFloatingValueList()
6094 {
6095     CSSParserValueList* list = new CSSParserValueList;
6096     m_floatingValueLists.add(list);
6097     return list;
6098 }
6099 
sinkFloatingValueList(CSSParserValueList * list)6100 CSSParserValueList* CSSParser::sinkFloatingValueList(CSSParserValueList* list)
6101 {
6102     if (list) {
6103         ASSERT(m_floatingValueLists.contains(list));
6104         m_floatingValueLists.remove(list);
6105     }
6106     return list;
6107 }
6108 
createFloatingFunction()6109 CSSParserFunction* CSSParser::createFloatingFunction()
6110 {
6111     CSSParserFunction* function = new CSSParserFunction;
6112     m_floatingFunctions.add(function);
6113     return function;
6114 }
6115 
sinkFloatingFunction(CSSParserFunction * function)6116 CSSParserFunction* CSSParser::sinkFloatingFunction(CSSParserFunction* function)
6117 {
6118     if (function) {
6119         ASSERT(m_floatingFunctions.contains(function));
6120         m_floatingFunctions.remove(function);
6121     }
6122     return function;
6123 }
6124 
sinkFloatingValue(CSSParserValue & value)6125 CSSParserValue& CSSParser::sinkFloatingValue(CSSParserValue& value)
6126 {
6127     if (value.unit == CSSParserValue::Function) {
6128         ASSERT(m_floatingFunctions.contains(value.function));
6129         m_floatingFunctions.remove(value.function);
6130     }
6131     return value;
6132 }
6133 
createFloatingMediaQueryExp(const AtomicString & mediaFeature,CSSParserValueList * values)6134 MediaQueryExp* CSSParser::createFloatingMediaQueryExp(const AtomicString& mediaFeature, CSSParserValueList* values)
6135 {
6136     m_floatingMediaQueryExp = MediaQueryExp::create(mediaFeature, values);
6137     return m_floatingMediaQueryExp.get();
6138 }
6139 
sinkFloatingMediaQueryExp(MediaQueryExp * expression)6140 PassOwnPtr<MediaQueryExp> CSSParser::sinkFloatingMediaQueryExp(MediaQueryExp* expression)
6141 {
6142     ASSERT_UNUSED(expression, expression == m_floatingMediaQueryExp);
6143     return m_floatingMediaQueryExp.release();
6144 }
6145 
createFloatingMediaQueryExpList()6146 Vector<OwnPtr<MediaQueryExp> >* CSSParser::createFloatingMediaQueryExpList()
6147 {
6148     m_floatingMediaQueryExpList = adoptPtr(new Vector<OwnPtr<MediaQueryExp> >);
6149     return m_floatingMediaQueryExpList.get();
6150 }
6151 
sinkFloatingMediaQueryExpList(Vector<OwnPtr<MediaQueryExp>> * list)6152 PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > CSSParser::sinkFloatingMediaQueryExpList(Vector<OwnPtr<MediaQueryExp> >* list)
6153 {
6154     ASSERT_UNUSED(list, list == m_floatingMediaQueryExpList);
6155     return m_floatingMediaQueryExpList.release();
6156 }
6157 
createFloatingMediaQuery(MediaQuery::Restrictor restrictor,const String & mediaType,PassOwnPtr<Vector<OwnPtr<MediaQueryExp>>> expressions)6158 MediaQuery* CSSParser::createFloatingMediaQuery(MediaQuery::Restrictor restrictor, const String& mediaType, PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > expressions)
6159 {
6160     m_floatingMediaQuery = adoptPtr(new MediaQuery(restrictor, mediaType, expressions));
6161     return m_floatingMediaQuery.get();
6162 }
6163 
createFloatingMediaQuery(PassOwnPtr<Vector<OwnPtr<MediaQueryExp>>> expressions)6164 MediaQuery* CSSParser::createFloatingMediaQuery(PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > expressions)
6165 {
6166     return createFloatingMediaQuery(MediaQuery::None, "all", expressions);
6167 }
6168 
sinkFloatingMediaQuery(MediaQuery * query)6169 PassOwnPtr<MediaQuery> CSSParser::sinkFloatingMediaQuery(MediaQuery* query)
6170 {
6171     ASSERT_UNUSED(query, query == m_floatingMediaQuery);
6172     return m_floatingMediaQuery.release();
6173 }
6174 
createMediaList()6175 MediaList* CSSParser::createMediaList()
6176 {
6177     RefPtr<MediaList> list = MediaList::create();
6178     MediaList* result = list.get();
6179     m_parsedStyleObjects.append(list.release());
6180     return result;
6181 }
6182 
createCharsetRule(const CSSParserString & charset)6183 CSSRule* CSSParser::createCharsetRule(const CSSParserString& charset)
6184 {
6185     if (!m_styleSheet)
6186         return 0;
6187     RefPtr<CSSCharsetRule> rule = CSSCharsetRule::create(m_styleSheet, charset);
6188     CSSCharsetRule* result = rule.get();
6189     m_parsedStyleObjects.append(rule.release());
6190     return result;
6191 }
6192 
createImportRule(const CSSParserString & url,MediaList * media)6193 CSSRule* CSSParser::createImportRule(const CSSParserString& url, MediaList* media)
6194 {
6195     if (!media || !m_styleSheet || !m_allowImportRules)
6196         return 0;
6197     RefPtr<CSSImportRule> rule = CSSImportRule::create(m_styleSheet, url, media);
6198     CSSImportRule* result = rule.get();
6199     m_parsedStyleObjects.append(rule.release());
6200     return result;
6201 }
6202 
createMediaRule(MediaList * media,CSSRuleList * rules)6203 CSSRule* CSSParser::createMediaRule(MediaList* media, CSSRuleList* rules)
6204 {
6205     if (!media || !rules || !m_styleSheet)
6206         return 0;
6207     m_allowImportRules = m_allowNamespaceDeclarations = false;
6208     RefPtr<CSSMediaRule> rule = CSSMediaRule::create(m_styleSheet, media, rules);
6209     CSSMediaRule* result = rule.get();
6210     m_parsedStyleObjects.append(rule.release());
6211     return result;
6212 }
6213 
createRuleList()6214 CSSRuleList* CSSParser::createRuleList()
6215 {
6216     RefPtr<CSSRuleList> list = CSSRuleList::create();
6217     CSSRuleList* listPtr = list.get();
6218 
6219     m_parsedRuleLists.append(list.release());
6220     return listPtr;
6221 }
6222 
createKeyframesRule()6223 WebKitCSSKeyframesRule* CSSParser::createKeyframesRule()
6224 {
6225     m_allowImportRules = m_allowNamespaceDeclarations = false;
6226     RefPtr<WebKitCSSKeyframesRule> rule = WebKitCSSKeyframesRule::create(m_styleSheet);
6227     WebKitCSSKeyframesRule* rulePtr = rule.get();
6228     m_parsedStyleObjects.append(rule.release());
6229     return rulePtr;
6230 }
6231 
createStyleRule(Vector<OwnPtr<CSSParserSelector>> * selectors)6232 CSSRule* CSSParser::createStyleRule(Vector<OwnPtr<CSSParserSelector> >* selectors)
6233 {
6234     CSSStyleRule* result = 0;
6235     markRuleBodyEnd();
6236     if (selectors) {
6237         m_allowImportRules = m_allowNamespaceDeclarations = false;
6238         RefPtr<CSSStyleRule> rule = CSSStyleRule::create(m_styleSheet, m_lastSelectorLineNumber);
6239         rule->adoptSelectorVector(*selectors);
6240         if (m_hasFontFaceOnlyValues)
6241             deleteFontFaceOnlyValues();
6242         rule->setDeclaration(CSSMutableStyleDeclaration::create(rule.get(), m_parsedProperties, m_numParsedProperties));
6243         result = rule.get();
6244         m_parsedStyleObjects.append(rule.release());
6245         if (m_ruleRangeMap) {
6246             ASSERT(m_currentRuleData);
6247             m_currentRuleData->styleSourceData->styleBodyRange = m_ruleBodyRange;
6248             m_currentRuleData->selectorListRange = m_selectorListRange;
6249             m_ruleRangeMap->set(result, m_currentRuleData.release());
6250             m_currentRuleData = CSSRuleSourceData::create();
6251             m_currentRuleData->styleSourceData = CSSStyleSourceData::create();
6252             m_inStyleRuleOrDeclaration = false;
6253         }
6254     }
6255     resetSelectorListMarks();
6256     resetRuleBodyMarks();
6257     clearProperties();
6258     return result;
6259 }
6260 
createFontFaceRule()6261 CSSRule* CSSParser::createFontFaceRule()
6262 {
6263     m_allowImportRules = m_allowNamespaceDeclarations = false;
6264     for (unsigned i = 0; i < m_numParsedProperties; ++i) {
6265         CSSProperty* property = m_parsedProperties[i];
6266         int id = property->id();
6267         if (id == CSSPropertyFontVariant && property->value()->isPrimitiveValue()) {
6268             RefPtr<CSSValue> value = property->m_value.release();
6269             property->m_value = CSSValueList::createCommaSeparated();
6270             static_cast<CSSValueList*>(property->value())->append(value.release());
6271         } else if (id == CSSPropertyFontFamily && (!property->value()->isValueList() || static_cast<CSSValueList*>(property->value())->length() != 1)) {
6272             // Unlike font-family property, font-family descriptor in @font-face rule
6273             // has to be a value list with exactly one family name. It cannot have a
6274             // have 'initial' value and cannot 'inherit' from parent.
6275             // See http://dev.w3.org/csswg/css3-fonts/#font-family-desc
6276             clearProperties();
6277             return 0;
6278         }
6279     }
6280     RefPtr<CSSFontFaceRule> rule = CSSFontFaceRule::create(m_styleSheet);
6281     rule->setDeclaration(CSSMutableStyleDeclaration::create(rule.get(), m_parsedProperties, m_numParsedProperties));
6282     clearProperties();
6283     CSSFontFaceRule* result = rule.get();
6284     m_parsedStyleObjects.append(rule.release());
6285     return result;
6286 }
6287 
addNamespace(const AtomicString & prefix,const AtomicString & uri)6288 void CSSParser::addNamespace(const AtomicString& prefix, const AtomicString& uri)
6289 {
6290     if (!m_styleSheet || !m_allowNamespaceDeclarations)
6291         return;
6292     m_allowImportRules = false;
6293     m_styleSheet->addNamespace(this, prefix, uri);
6294 }
6295 
updateSpecifiersWithElementName(const AtomicString & namespacePrefix,const AtomicString & elementName,CSSParserSelector * specifiers)6296 void CSSParser::updateSpecifiersWithElementName(const AtomicString& namespacePrefix, const AtomicString& elementName, CSSParserSelector* specifiers)
6297 {
6298     AtomicString determinedNamespace = namespacePrefix != nullAtom && m_styleSheet ? m_styleSheet->determineNamespace(namespacePrefix) : m_defaultNamespace;
6299     QualifiedName tag = QualifiedName(namespacePrefix, elementName, determinedNamespace);
6300     if (!specifiers->isUnknownPseudoElement()) {
6301         specifiers->setTag(tag);
6302         return;
6303     }
6304 
6305     CSSParserSelector* lastShadowDescendant = specifiers;
6306     CSSParserSelector* history = specifiers;
6307     while (history->tagHistory()) {
6308         history = history->tagHistory();
6309         if (history->hasShadowDescendant())
6310             lastShadowDescendant = history;
6311     }
6312 
6313     if (lastShadowDescendant->tagHistory()) {
6314         lastShadowDescendant->tagHistory()->setTag(tag);
6315         return;
6316     }
6317 
6318     // No need to create an extra element name selector if we are matching any element
6319     // in any namespace.
6320     if (elementName == starAtom && m_defaultNamespace == starAtom)
6321         return;
6322 
6323     OwnPtr<CSSParserSelector> elementNameSelector = adoptPtr(new CSSParserSelector);
6324     elementNameSelector->setTag(tag);
6325     lastShadowDescendant->setTagHistory(elementNameSelector.release());
6326     lastShadowDescendant->setRelation(CSSSelector::ShadowDescendant);
6327 }
6328 
updateSpecifiers(CSSParserSelector * specifiers,CSSParserSelector * newSpecifier)6329 CSSParserSelector* CSSParser::updateSpecifiers(CSSParserSelector* specifiers, CSSParserSelector* newSpecifier)
6330 {
6331     if (newSpecifier->isUnknownPseudoElement()) {
6332         // Unknown pseudo element always goes at the top of selector chain.
6333         newSpecifier->appendTagHistory(CSSSelector::ShadowDescendant, sinkFloatingSelector(specifiers));
6334         return newSpecifier;
6335     }
6336     if (specifiers->isUnknownPseudoElement()) {
6337         // Specifiers for unknown pseudo element go right behind it in the chain.
6338         specifiers->insertTagHistory(CSSSelector::SubSelector, sinkFloatingSelector(newSpecifier), CSSSelector::ShadowDescendant);
6339         return specifiers;
6340     }
6341     specifiers->appendTagHistory(CSSSelector::SubSelector, sinkFloatingSelector(newSpecifier));
6342     return specifiers;
6343 }
6344 
createPageRule(PassOwnPtr<CSSParserSelector> pageSelector)6345 CSSRule* CSSParser::createPageRule(PassOwnPtr<CSSParserSelector> pageSelector)
6346 {
6347     // FIXME: Margin at-rules are ignored.
6348     m_allowImportRules = m_allowNamespaceDeclarations = false;
6349     CSSPageRule* pageRule = 0;
6350     if (pageSelector) {
6351         RefPtr<CSSPageRule> rule = CSSPageRule::create(m_styleSheet, m_lastSelectorLineNumber);
6352         Vector<OwnPtr<CSSParserSelector> > selectorVector;
6353         selectorVector.append(pageSelector);
6354         rule->adoptSelectorVector(selectorVector);
6355         rule->setDeclaration(CSSMutableStyleDeclaration::create(rule.get(), m_parsedProperties, m_numParsedProperties));
6356         pageRule = rule.get();
6357         m_parsedStyleObjects.append(rule.release());
6358     }
6359     clearProperties();
6360     return pageRule;
6361 }
6362 
createMarginAtRule(CSSSelector::MarginBoxType)6363 CSSRule* CSSParser::createMarginAtRule(CSSSelector::MarginBoxType /* marginBox */)
6364 {
6365     // FIXME: Implement margin at-rule here, using:
6366     //        - marginBox: margin box
6367     //        - m_parsedProperties: properties at [m_numParsedPropertiesBeforeMarginBox, m_numParsedProperties) are for this at-rule.
6368     // Don't forget to also update the action for page symbol in CSSGrammar.y such that margin at-rule data is cleared if page_selector is invalid.
6369 
6370     endDeclarationsForMarginBox();
6371     return 0; // until this method is implemented.
6372 }
6373 
startDeclarationsForMarginBox()6374 void CSSParser::startDeclarationsForMarginBox()
6375 {
6376     m_numParsedPropertiesBeforeMarginBox = m_numParsedProperties;
6377 }
6378 
endDeclarationsForMarginBox()6379 void CSSParser::endDeclarationsForMarginBox()
6380 {
6381     ASSERT(m_numParsedPropertiesBeforeMarginBox != INVALID_NUM_PARSED_PROPERTIES);
6382     rollbackLastProperties(m_numParsedProperties - m_numParsedPropertiesBeforeMarginBox);
6383     m_numParsedPropertiesBeforeMarginBox = INVALID_NUM_PARSED_PROPERTIES;
6384 }
6385 
deleteFontFaceOnlyValues()6386 void CSSParser::deleteFontFaceOnlyValues()
6387 {
6388     ASSERT(m_hasFontFaceOnlyValues);
6389     int deletedProperties = 0;
6390 
6391     for (unsigned i = 0; i < m_numParsedProperties; ++i) {
6392         CSSProperty* property = m_parsedProperties[i];
6393         int id = property->id();
6394         if (id == CSSPropertyFontVariant && property->value()->isValueList()) {
6395             delete property;
6396             deletedProperties++;
6397         } else if (deletedProperties)
6398             m_parsedProperties[i - deletedProperties] = m_parsedProperties[i];
6399     }
6400 
6401     m_numParsedProperties -= deletedProperties;
6402 }
6403 
createKeyframeRule(CSSParserValueList * keys)6404 WebKitCSSKeyframeRule* CSSParser::createKeyframeRule(CSSParserValueList* keys)
6405 {
6406     // Create a key string from the passed keys
6407     String keyString;
6408     for (unsigned i = 0; i < keys->size(); ++i) {
6409         float key = (float) keys->valueAt(i)->fValue;
6410         if (i != 0)
6411             keyString += ",";
6412         keyString += String::number(key);
6413         keyString += "%";
6414     }
6415 
6416     RefPtr<WebKitCSSKeyframeRule> keyframe = WebKitCSSKeyframeRule::create(m_styleSheet);
6417     keyframe->setKeyText(keyString);
6418     keyframe->setDeclaration(CSSMutableStyleDeclaration::create(0, m_parsedProperties, m_numParsedProperties));
6419 
6420     clearProperties();
6421 
6422     WebKitCSSKeyframeRule* keyframePtr = keyframe.get();
6423     m_parsedStyleObjects.append(keyframe.release());
6424     return keyframePtr;
6425 }
6426 
invalidBlockHit()6427 void CSSParser::invalidBlockHit()
6428 {
6429     if (m_styleSheet && !m_hadSyntacticallyValidCSSRule)
6430         m_styleSheet->setHasSyntacticallyValidCSSHeader(false);
6431 }
6432 
updateLastSelectorLineAndPosition()6433 void CSSParser::updateLastSelectorLineAndPosition()
6434 {
6435     m_lastSelectorLineNumber = m_lineNumber;
6436     markRuleBodyStart();
6437 }
6438 
markSelectorListStart()6439 void CSSParser::markSelectorListStart()
6440 {
6441     m_selectorListRange.start = yytext - m_data;
6442 }
6443 
markSelectorListEnd()6444 void CSSParser::markSelectorListEnd()
6445 {
6446     if (!m_currentRuleData)
6447         return;
6448     UChar* listEnd = yytext;
6449     while (listEnd > m_data + 1) {
6450         if (isHTMLSpace(*(listEnd - 1)))
6451             --listEnd;
6452         else
6453             break;
6454     }
6455     m_selectorListRange.end = listEnd - m_data;
6456 }
6457 
markRuleBodyStart()6458 void CSSParser::markRuleBodyStart()
6459 {
6460     unsigned offset = yytext - m_data;
6461     if (*yytext == '{')
6462         ++offset; // Skip the rule body opening brace.
6463     if (offset > m_ruleBodyRange.start)
6464         m_ruleBodyRange.start = offset;
6465     m_inStyleRuleOrDeclaration = true;
6466 }
6467 
markRuleBodyEnd()6468 void CSSParser::markRuleBodyEnd()
6469 {
6470     unsigned offset = yytext - m_data;
6471     if (offset > m_ruleBodyRange.end)
6472         m_ruleBodyRange.end = offset;
6473 }
6474 
markPropertyStart()6475 void CSSParser::markPropertyStart()
6476 {
6477     if (!m_inStyleRuleOrDeclaration)
6478         return;
6479     m_propertyRange.start = yytext - m_data;
6480 }
6481 
markPropertyEnd(bool isImportantFound,bool isPropertyParsed)6482 void CSSParser::markPropertyEnd(bool isImportantFound, bool isPropertyParsed)
6483 {
6484     if (!m_inStyleRuleOrDeclaration)
6485         return;
6486     unsigned offset = yytext - m_data;
6487     if (*yytext == ';') // Include semicolon into the property text.
6488         ++offset;
6489     m_propertyRange.end = offset;
6490     if (m_propertyRange.start != UINT_MAX && m_currentRuleData) {
6491         // This stuff is only executed when the style data retrieval is requested by client.
6492         const unsigned start = m_propertyRange.start;
6493         const unsigned end = m_propertyRange.end;
6494         ASSERT(start < end);
6495         String propertyString = String(m_data + start, end - start).stripWhiteSpace();
6496         if (propertyString.endsWith(";", true))
6497             propertyString = propertyString.left(propertyString.length() - 1);
6498         Vector<String> propertyComponents;
6499         size_t colonIndex = propertyString.find(":");
6500         ASSERT(colonIndex != notFound);
6501 
6502         String name = propertyString.left(colonIndex).stripWhiteSpace();
6503         String value = propertyString.substring(colonIndex + 1, propertyString.length()).stripWhiteSpace();
6504         // The property range is relative to the declaration start offset.
6505         m_currentRuleData->styleSourceData->propertyData.append(
6506             CSSPropertySourceData(name, value, isImportantFound, isPropertyParsed, SourceRange(start - m_ruleBodyRange.start, end - m_ruleBodyRange.start)));
6507     }
6508     resetPropertyMarks();
6509 }
6510 
cssPropertyID(const UChar * propertyName,unsigned length)6511 static int cssPropertyID(const UChar* propertyName, unsigned length)
6512 {
6513     if (!length)
6514         return 0;
6515     if (length > maxCSSPropertyNameLength)
6516         return 0;
6517 
6518     char buffer[maxCSSPropertyNameLength + 1 + 1]; // 1 to turn "apple"/"khtml" into "webkit", 1 for null character
6519 
6520     for (unsigned i = 0; i != length; ++i) {
6521         UChar c = propertyName[i];
6522         if (c == 0 || c >= 0x7F)
6523             return 0; // illegal character
6524         buffer[i] = toASCIILower(c);
6525     }
6526     buffer[length] = '\0';
6527 
6528     const char* name = buffer;
6529     if (buffer[0] == '-') {
6530         // If the prefix is -apple- or -khtml-, change it to -webkit-.
6531         // This makes the string one character longer.
6532         if (hasPrefix(buffer, length, "-apple-") || hasPrefix(buffer, length, "-khtml-")) {
6533             memmove(buffer + 7, buffer + 6, length + 1 - 6);
6534             memcpy(buffer, "-webkit", 7);
6535             ++length;
6536         }
6537 
6538 #if PLATFORM(IOS)
6539         if (!strcmp(buffer, "-webkit-hyphenate-locale")) {
6540             // Worked in iOS 4.2.
6541             const char* const webkitLocale = "-webkit-locale";
6542             name = webkitLocale;
6543             length = strlen(webkitLocale);
6544         }
6545 #endif
6546     }
6547 
6548     const Property* hashTableEntry = findProperty(name, length);
6549     return hashTableEntry ? hashTableEntry->id : 0;
6550 }
6551 
cssPropertyID(const String & string)6552 int cssPropertyID(const String& string)
6553 {
6554     return cssPropertyID(string.characters(), string.length());
6555 }
6556 
cssPropertyID(const CSSParserString & string)6557 int cssPropertyID(const CSSParserString& string)
6558 {
6559     return cssPropertyID(string.characters, string.length);
6560 }
6561 
cssValueKeywordID(const CSSParserString & string)6562 int cssValueKeywordID(const CSSParserString& string)
6563 {
6564     unsigned length = string.length;
6565     if (!length)
6566         return 0;
6567     if (length > maxCSSValueKeywordLength)
6568         return 0;
6569 
6570     char buffer[maxCSSValueKeywordLength + 1 + 1]; // 1 to turn "apple"/"khtml" into "webkit", 1 for null character
6571 
6572     for (unsigned i = 0; i != length; ++i) {
6573         UChar c = string.characters[i];
6574         if (c == 0 || c >= 0x7F)
6575             return 0; // illegal character
6576         buffer[i] = WTF::toASCIILower(c);
6577     }
6578     buffer[length] = '\0';
6579 
6580     if (buffer[0] == '-') {
6581         // If the prefix is -apple- or -khtml-, change it to -webkit-.
6582         // This makes the string one character longer.
6583         if (hasPrefix(buffer, length, "-apple-") || hasPrefix(buffer, length, "-khtml-")) {
6584             memmove(buffer + 7, buffer + 6, length + 1 - 6);
6585             memcpy(buffer, "-webkit", 7);
6586             ++length;
6587         }
6588     }
6589 
6590     const Value* hashTableEntry = findValue(buffer, length);
6591     return hashTableEntry ? hashTableEntry->id : 0;
6592 }
6593 
6594 // "ident" from the CSS tokenizer, minus backslash-escape sequences
isCSSTokenizerIdentifier(const String & string)6595 static bool isCSSTokenizerIdentifier(const String& string)
6596 {
6597     const UChar* p = string.characters();
6598     const UChar* end = p + string.length();
6599 
6600     // -?
6601     if (p != end && p[0] == '-')
6602         ++p;
6603 
6604     // {nmstart}
6605     if (p == end || !(p[0] == '_' || p[0] >= 128 || isASCIIAlpha(p[0])))
6606         return false;
6607     ++p;
6608 
6609     // {nmchar}*
6610     for (; p != end; ++p) {
6611         if (!(p[0] == '_' || p[0] == '-' || p[0] >= 128 || isASCIIAlphanumeric(p[0])))
6612             return false;
6613     }
6614 
6615     return true;
6616 }
6617 
6618 // "url" from the CSS tokenizer, minus backslash-escape sequences
isCSSTokenizerURL(const String & string)6619 static bool isCSSTokenizerURL(const String& string)
6620 {
6621     const UChar* p = string.characters();
6622     const UChar* end = p + string.length();
6623 
6624     for (; p != end; ++p) {
6625         UChar c = p[0];
6626         switch (c) {
6627             case '!':
6628             case '#':
6629             case '$':
6630             case '%':
6631             case '&':
6632                 break;
6633             default:
6634                 if (c < '*')
6635                     return false;
6636                 if (c <= '~')
6637                     break;
6638                 if (c < 128)
6639                     return false;
6640         }
6641     }
6642 
6643     return true;
6644 }
6645 
6646 // We use single quotes for now because markup.cpp uses double quotes.
quoteCSSString(const String & string)6647 String quoteCSSString(const String& string)
6648 {
6649     // For efficiency, we first pre-calculate the length of the quoted string, then we build the actual one.
6650     // Please see below for the actual logic.
6651     unsigned quotedStringSize = 2; // Two quotes surrounding the entire string.
6652     bool afterEscape = false;
6653     for (unsigned i = 0; i < string.length(); ++i) {
6654         UChar ch = string[i];
6655         if (ch == '\\' || ch == '\'') {
6656             quotedStringSize += 2;
6657             afterEscape = false;
6658         } else if (ch < 0x20 || ch == 0x7F) {
6659             quotedStringSize += 2 + (ch >= 0x10);
6660             afterEscape = true;
6661         } else {
6662             quotedStringSize += 1 + (afterEscape && (isASCIIHexDigit(ch) || ch == ' '));
6663             afterEscape = false;
6664         }
6665     }
6666 
6667     StringBuffer buffer(quotedStringSize);
6668     unsigned index = 0;
6669     buffer[index++] = '\'';
6670     afterEscape = false;
6671     for (unsigned i = 0; i < string.length(); ++i) {
6672         UChar ch = string[i];
6673         if (ch == '\\' || ch == '\'') {
6674             buffer[index++] = '\\';
6675             buffer[index++] = ch;
6676             afterEscape = false;
6677         } else if (ch < 0x20 || ch == 0x7F) { // Control characters.
6678             buffer[index++] = '\\';
6679             placeByteAsHexCompressIfPossible(ch, buffer, index, Lowercase);
6680             afterEscape = true;
6681         } else {
6682             // Space character may be required to separate backslash-escape sequence and normal characters.
6683             if (afterEscape && (isASCIIHexDigit(ch) || ch == ' '))
6684                 buffer[index++] = ' ';
6685             buffer[index++] = ch;
6686             afterEscape = false;
6687         }
6688     }
6689     buffer[index++] = '\'';
6690 
6691     ASSERT(quotedStringSize == index);
6692     return String::adopt(buffer);
6693 }
6694 
quoteCSSStringIfNeeded(const String & string)6695 String quoteCSSStringIfNeeded(const String& string)
6696 {
6697     return isCSSTokenizerIdentifier(string) ? string : quoteCSSString(string);
6698 }
6699 
quoteCSSURLIfNeeded(const String & string)6700 String quoteCSSURLIfNeeded(const String& string)
6701 {
6702     return isCSSTokenizerURL(string) ? string : quoteCSSString(string);
6703 }
6704 
isValidNthToken(const CSSParserString & token)6705 bool isValidNthToken(const CSSParserString& token)
6706 {
6707     // The tokenizer checks for the construct of an+b.
6708     // nth can also accept "n", "odd" or "even" but should not accept any other token.
6709     return equalIgnoringCase(token, "odd") || equalIgnoringCase(token, "even") || equalIgnoringCase(token, "n");
6710 }
6711 
6712 #define YY_DECL int CSSParser::lex()
6713 #define yyconst const
6714 typedef int yy_state_type;
6715 typedef unsigned YY_CHAR;
6716 // The following line makes sure we treat non-Latin-1 Unicode characters correctly.
6717 #define YY_SC_TO_UI(c) (c > 0xff ? 0xff : c)
6718 #define YY_DO_BEFORE_ACTION \
6719         yytext = yy_bp; \
6720         yyleng = (int) (yy_cp - yy_bp); \
6721         yy_hold_char = *yy_cp; \
6722         *yy_cp = 0; \
6723         yy_c_buf_p = yy_cp;
6724 #define YY_BREAK break;
6725 #define ECHO
6726 #define YY_RULE_SETUP
6727 #define INITIAL 0
6728 #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
6729 #define yyterminate() yyTok = END_TOKEN; return yyTok
6730 #define YY_FATAL_ERROR(a)
6731 // The following line is needed to build the tokenizer with a condition stack.
6732 // The macro is used in the tokenizer grammar with lines containing
6733 // BEGIN(mediaqueries) and BEGIN(initial). yy_start acts as index to
6734 // tokenizer transition table, and 'mediaqueries' and 'initial' are
6735 // offset multipliers that specify which transitions are active
6736 // in the tokenizer during in each condition (tokenizer state).
6737 #define BEGIN yy_start = 1 + 2 *
6738 
6739 #include "tokenizer.cpp"
6740 
6741 }
6742