/*
 * Copyright (C) 2009 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// Generate js file as follows:
//
// re2c -isc Source/WebCore/inspector/front-end/SourceCSSTokenizer.re2js \
// | sed 's|^yy\([^:]*\)*\:|case \1:|' \
// | sed 's|[*]cursor[+][+]|this._charAt(cursor++)|' \
// | sed 's|[[*][+][+]cursor|this._charAt(++cursor)|' \
// | sed 's|[*]cursor|this._charAt(cursor)|' \
// | sed 's|yych = \*\([^;]*\)|yych = this._charAt\1|' \
// | sed 's|goto case \([^;]*\)|{ gotoCase = \1; continue; }|' \
// | sed 's|unsigned\ int|var|' \
// | sed 's|var\ yych|case 1: var yych|'

/**
 * @constructor
 * @extends {WebInspector.SourceTokenizer}
 */
WebInspector.SourceCSSTokenizer = function()
{
    WebInspector.SourceTokenizer.call(this);

    this._propertyKeywords = WebInspector.CSSCompletions.cssNameCompletions.keySet();
    this._colorKeywords = WebInspector.CSSKeywordCompletions.colors();

    this._valueKeywords = [
        "above", "absolute", "activeborder", "activecaption", "afar", "after-white-space", "ahead", "alias", "all", "all-scroll",
        "alternate", "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", "arabic-indic", "armenian", "asterisks",
        "auto", "avoid", "background", "backwards", "baseline", "below", "bidi-override", "binary", "bengali", "blink",
        "block", "block-axis", "bold", "bolder", "border", "border-box", "both", "bottom", "break-all", "break-word", "button",
        "button-bevel", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian", "capitalize", "caps-lock-indicator",
        "caption", "captiontext", "caret", "cell", "center", "checkbox", "circle", "cjk-earthly-branch", "cjk-heavenly-stem", "cjk-ideographic",
        "clear", "clip", "close-quote", "col-resize", "collapse", "compact", "condensed", "contain", "content", "content-box", "context-menu",
        "continuous", "copy", "cover", "crop", "cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal", "decimal-leading-zero", "default",
        "default-button", "destination-atop", "destination-in", "destination-out", "destination-over", "devanagari", "disc", "discard", "document",
        "dot-dash", "dot-dot-dash", "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", "element",
        "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", "ethiopic-abegede-am-et", "ethiopic-abegede-gez",
        "ethiopic-abegede-ti-er", "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", "ethiopic-halehame-aa-et",
        "ethiopic-halehame-am-et", "ethiopic-halehame-gez", "ethiopic-halehame-om-et", "ethiopic-halehame-sid-et",
        "ethiopic-halehame-so-et", "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", "ew-resize", "expanded",
        "extra-condensed", "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "footnotes", "forwards", "from", "geometricPrecision",
        "georgian", "graytext", "groove", "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew", "help",
        "hidden", "hide", "higher", "highlight", "highlighttext", "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore",
        "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext", "inherit", "initial", "inline",
        "inline-axis", "inline-block", "inline-table", "inset", "inside", "intrinsic", "invert", "italic", "justify", "kannada", "katakana",
        "katakana-iroha", "khmer", "landscape", "lao", "large", "larger", "left", "level", "lighter", "line-through", "linear", "lines",
        "list-button", "list-item", "listbox", "listitem", "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", "lower-greek",
        "lower-hexadecimal", "lower-latin", "lower-norwegian", "lower-roman", "lowercase", "ltr", "malayalam", "match", "media-controls-background",
        "media-current-time-display", "media-fullscreen-button", "media-mute-button", "media-play-button", "media-return-to-realtime-button",
        "media-rewind-button", "media-seek-back-button", "media-seek-forward-button", "media-slider", "media-sliderthumb", "media-time-remaining-display",
        "media-volume-slider", "media-volume-slider-container", "media-volume-sliderthumb", "medium", "menu", "menulist", "menulist-button",
        "menulist-text", "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", "mix", "mongolian", "monospace", "move", "multiple",
        "myanmar", "n-resize", "narrower", "navy", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", "no-open-quote", "no-repeat", "none",
        "normal", "not-allowed", "nowrap", "ns-resize", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote", "optimizeLegibility",
        "optimizeSpeed", "oriya", "oromo", "outset", "outside", "overlay", "overline", "padding", "padding-box", "painted", "paused",
        "persian", "plus-darker", "plus-lighter", "pointer", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", "progress",
        "push-button", "radio", "read-only", "read-write", "read-write-plaintext-only", "relative", "repeat", "repeat-x",
        "repeat-y", "reset", "reverse", "rgb", "rgba", "ridge", "right", "round", "row-resize", "rtl", "run-in", "running", "s-resize", "sans-serif",
        "scroll", "scrollbar", "se-resize", "searchfield", "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button",
        "searchfield-results-decoration", "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", "single",
        "skip-white-space", "slide", "slider-horizontal", "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
        "small", "small-caps", "small-caption", "smaller", "solid", "somali", "source-atop", "source-in", "source-out", "source-over",
        "space", "square", "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub", "subpixel-antialiased", "super",
        "sw-resize", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group",
        "table-row", "table-row-group", "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", "thick", "thin",
        "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", "tigrinya-er-abegede",
        "tigrinya-et", "tigrinya-et-abegede", "to", "top", "transparent", "ultra-condensed", "ultra-expanded", "underline", "up", "upper-alpha", "upper-armenian",
        "upper-greek", "upper-hexadecimal", "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", "vertical", "vertical-text", "visible",
        "visibleFill", "visiblePainted", "visibleStroke", "visual", "w-resize", "wait", "wave", "white", "wider", "window", "windowframe", "windowtext",
        "x-large", "x-small", "xor", "xx-large", "xx-small", "yellow", "-wap-marquee", "-webkit-activelink", "-webkit-auto", "-webkit-baseline-middle",
        "-webkit-body", "-webkit-box", "-webkit-center", "-webkit-control", "-webkit-focus-ring-color", "-webkit-grab", "-webkit-grabbing",
        "-webkit-gradient", "-webkit-inline-box", "-webkit-left", "-webkit-link", "-webkit-marquee", "-webkit-mini-control", "-webkit-nowrap", "-webkit-pictograph",
        "-webkit-right", "-webkit-small-control", "-webkit-text", "-webkit-xxx-large", "-webkit-zoom-in", "-webkit-zoom-out",
    ].keySet();

    this._mediaTypes = ["all", "aural", "braille", "embossed", "handheld", "import", "print", "projection", "screen", "tty", "tv"].keySet();

    this._lexConditions = {
        INITIAL: 0,
        COMMENT: 1,
        DSTRING: 2,
        SSTRING: 3
    };

    this._parseConditions = {
        INITIAL: 0,
        PROPERTY: 1,
        PROPERTY_VALUE: 2,
        AT_RULE: 3
    };

    this.case_INITIAL = 1000;
    this.case_COMMENT = 1002;
    this.case_DSTRING = 1003;
    this.case_SSTRING = 1004;

    this.condition = this.createInitialCondition();
}

WebInspector.SourceCSSTokenizer.prototype = {
    createInitialCondition: function()
    {
        return { lexCondition: this._lexConditions.INITIAL, parseCondition: this._parseConditions.INITIAL };
    },

    /**
     * @param {boolean=} stringEnds
     */
    _stringToken: function(cursor, stringEnds)
    {
        if (this._isPropertyValue())
            this.tokenType = "css-string";
        else
            this.tokenType = null;
        return cursor;
    },

    _isPropertyValue: function()
    {
        return this._condition.parseCondition === this._parseConditions.PROPERTY_VALUE || this._condition.parseCondition === this._parseConditions.AT_RULE;
    },

    nextToken: function(cursor)
    {
        var cursorOnEnter = cursor;
        var gotoCase = 1;
        var YYMARKER;
        while (1) {
            switch (gotoCase)
            // Following comment is replaced with generated state machine.
            /*!re2c
                re2c:define:YYCTYPE  = "var";
                re2c:define:YYCURSOR = cursor;
                re2c:define:YYGETCONDITION = "this.getLexCondition";
                re2c:define:YYSETCONDITION = "this.setLexCondition";
                re2c:condprefix = "case this.case_";
                re2c:condenumprefix = "this._lexConditions.";
                re2c:yyfill:enable = 0;
                re2c:labelprefix = "case ";
                re2c:indent:top = 2;
                re2c:indent:string = "    ";

                CommentContent = ([^*\r\n] | ("*"+[^/*]))*;
                Comment = "/*" CommentContent "*"+ "/";
                CommentStart = "/*" CommentContent [\r\n];
                CommentEnd = CommentContent "*"+ "/";

                OpenCurlyBracket = "{";
                CloseCurlyBracket = "}";

                Colon = ":";
                Semicolon = ";";

                NumericLiteral = "-"? ([0-9]+ | [0-9]* "." [0-9]+)  ("em" | "rem" | "__qem" | "ex" | "px" | "cm" |
                    "mm" | "in" | "pt" | "pc" | "deg" | "rad" | "grad" | "turn" | "ms" | "s" | "Hz" | "kHz" | "%")?;

                Color = "#" [0-9A-Fa-f]+;
                Identifier = [@!_\-$0-9a-zA-Z\[\]='"/]+;

                DoubleStringContent = ([^\r\n\"\\] | "\\" ['"\\bfnrtv])*;
                SingleStringContent = ([^\r\n\'\\] | "\\" ['"\\bfnrtv])*;
                StringLiteral = "\"" DoubleStringContent "\"" | "'" SingleStringContent "'";
                DoubleStringStart = "\"" DoubleStringContent "\\" [\r\n];
                DoubleStringEnd = DoubleStringContent "\"";
                SingleStringStart = "'" SingleStringContent "\\" [\r\n];
                SingleStringEnd = SingleStringContent "'";

                <INITIAL> Comment { this.tokenType = "css-comment"; return cursor; }
                <INITIAL> CommentStart => COMMENT { this.tokenType = "css-comment"; return cursor; }
                <COMMENT> CommentContent => COMMENT { this.tokenType = "css-comment"; return cursor; }
                <COMMENT> CommentEnd => INITIAL { this.tokenType = "css-comment"; return cursor; }

                <INITIAL> StringLiteral { return this._stringToken(cursor, true); }
                <INITIAL> DoubleStringStart => DSTRING { return this._stringToken(cursor); }
                <DSTRING> DoubleStringContent => DSTRING { return this._stringToken(cursor); }
                <DSTRING> DoubleStringEnd => INITIAL { return this._stringToken(cursor, true); }
                <INITIAL> SingleStringStart => SSTRING { return this._stringToken(cursor); }
                <SSTRING> SingleStringContent => SSTRING { return this._stringToken(cursor); }
                <SSTRING> SingleStringEnd => INITIAL { return this._stringToken(cursor, true); }

                <INITIAL> OpenCurlyBracket
                {
                    this.tokenType = null;
                    if (this._condition.parseCondition === this._parseConditions.AT_RULE)
                        this._condition.parseCondition = this._parseConditions.INITIAL;
                    else
                        this._condition.parseCondition = this._parseConditions.PROPERTY;
                    return cursor;
                }

                <INITIAL> CloseCurlyBracket
                {
                    this.tokenType = null;
                    this._condition.parseCondition = this._parseConditions.INITIAL;
                    return cursor;
                }

                <INITIAL> Colon
                {
                    this.tokenType = null;
                    if (this._condition.parseCondition === this._parseConditions.PROPERTY)
                        this._condition.parseCondition = this._parseConditions.PROPERTY_VALUE;
                    return cursor;
                }

                <INITIAL> Semicolon
                {
                    this.tokenType = null;
                    if (this._condition.parseCondition === this._parseConditions.AT_RULE)
                        this._condition.parseCondition = this._parseConditions.INITIAL;
                    else
                        this._condition.parseCondition = this._parseConditions.PROPERTY;
                    return cursor;
                }

                <INITIAL> NumericLiteral
                {
                    if (this._isPropertyValue())
                        this.tokenType = "css-number";
                    else
                        this.tokenType = null;
                    return cursor;
                }

                <INITIAL> Color
                {
                    if (this._isPropertyValue())
                        this.tokenType = "css-color";
                    else
                        this.tokenType = null;
                    return cursor;
                }

                <INITIAL> Identifier
                {
                    var token = this._line.substring(cursorOnEnter, cursor);
                    if (this._condition.parseCondition === this._parseConditions.INITIAL) {
                        if (token === "@import" || token === "@media") {
                            this.tokenType = "css-at-rule";
                            this._condition.parseCondition = this._parseConditions.AT_RULE;
                        } else if (token.indexOf("@") === 0)
                            this.tokenType = "css-at-rule";
                        else
                            this.tokenType = "css-selector";
                    }
                    else if (this._condition.parseCondition === this._parseConditions.AT_RULE && token in this._mediaTypes)
                        this.tokenType = "css-keyword";
                    else if (this._condition.parseCondition === this._parseConditions.PROPERTY && token in this._propertyKeywords)
                        this.tokenType = "css-property";
                    else if (this._isPropertyValue()) {
                        if (token in this._valueKeywords)
                            this.tokenType = "css-keyword";
                        else if (token in this._colorKeywords) {
                            // FIXME: this does not convert tokens toLowerCase() for the sake of speed.
                            this.tokenType = "css-color";
                        } else if (token === "!important")
                            this.tokenType = "css-important";
                    } else
                        this.tokenType = null;
                    return cursor;
                }
                <*> [^] { this.tokenType = null; return cursor; }
            */
        }
    }
}

WebInspector.SourceCSSTokenizer.prototype.__proto__ = WebInspector.SourceTokenizer.prototype;
