fsk119 commented on code in PR #22063:
URL: https://github.com/apache/flink/pull/22063#discussion_r1164053106


##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.client.cli.parser;
+
+import org.apache.flink.table.api.SqlDialect;
+import org.apache.flink.table.api.config.TableConfigOptions;
+import org.apache.flink.table.client.config.SqlClientOptions;
+import org.apache.flink.table.client.gateway.Executor;
+
+import org.jline.reader.LineReader;
+import org.jline.reader.impl.DefaultHighlighter;
+import org.jline.utils.AttributedString;
+import org.jline.utils.AttributedStringBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Properties;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/** Sql Client syntax highlighter. */
+public class SqlClientSyntaxHighlighter extends DefaultHighlighter {
+    private static final Logger LOG = 
LoggerFactory.getLogger(SqlClientSyntaxHighlighter.class);
+    private static Set<String> keywordSet;
+
+    static {
+        try (InputStream is =
+                
SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) {
+            Properties props = new Properties();
+            props.load(is);
+            keywordSet =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("default").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+        } catch (IOException e) {
+            LOG.error("Exception: ", e);
+            keywordSet = Collections.emptySet();
+        }
+    }
+
+    private final Executor executor;
+
+    public SqlClientSyntaxHighlighter(Executor executor) {
+        this.executor = executor;
+    }
+
+    @Override
+    public AttributedString highlight(LineReader reader, String buffer) {
+        final SyntaxHighlightStyle.BuiltInStyle style =
+                SyntaxHighlightStyle.BuiltInStyle.fromString(
+                        executor.getSessionConfig()
+                                
.get(SqlClientOptions.DISPLAY_DEFAULT_COLOR_SCHEMA));
+
+        if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) {
+            return super.highlight(reader, buffer);
+        }
+        final String dialectName =
+                
executor.getSessionConfig().get(TableConfigOptions.TABLE_SQL_DIALECT);
+        final SqlDialect dialect =
+                SqlDialect.HIVE.name().equalsIgnoreCase(dialectName)
+                        ? SqlDialect.HIVE
+                        : SqlDialect.DEFAULT;
+        return getHighlightedOutput(buffer, style.getHighlightStyle(), 
dialect);
+    }
+
+    static AttributedString getHighlightedOutput(
+            String buffer, SyntaxHighlightStyle style, SqlDialect dialect) {
+        final AttributedStringBuilder highlightedOutput = new 
AttributedStringBuilder();
+        State prevParseState = State.DEFAULT;
+        State currentParseState = State.DEFAULT;
+        final StringBuilder word = new StringBuilder();
+        for (int i = 0; i < buffer.length(); i++) {
+            final char currentChar = buffer.charAt(i);
+            if (prevParseState == State.DEFAULT) {
+                currentParseState = State.computeStateAt(buffer, i, dialect);
+                if (currentParseState == State.DEFAULT) {
+                    if (isPartOfWord(currentChar)) {
+                        word.append(currentChar);
+                    } else {
+                        handleWord(word, highlightedOutput, currentParseState, 
style);
+                        highlightedOutput.append(currentChar);
+                        word.setLength(0);
+                    }
+                } else {
+                    handleWord(word, highlightedOutput, State.DEFAULT, style);
+                    currentParseState.styleSetter.accept(highlightedOutput, 
style);
+                    highlightedOutput.append(currentParseState.start);
+                    i += currentParseState.start.length() - 1;
+                }
+            } else {
+                if (currentParseState.isEndOfState(buffer, i)) {
+                    highlightedOutput
+                            .append(word)
+                            .append(currentParseState.end)
+                            .style(style.getDefaultStyle());
+                    word.setLength(0);
+                    i += currentParseState.end.length() - 1;
+                    currentParseState = State.DEFAULT;
+                } else {
+                    word.append(currentChar);
+                }
+            }
+            prevParseState = currentParseState;
+        }
+        handleWord(word, highlightedOutput, currentParseState, style);
+        return highlightedOutput.toAttributedString();
+    }
+
+    private static boolean isPartOfWord(char c) {
+        return Character.isLetterOrDigit(c) || c == '_' || c == '$';
+    }
+
+    private static void handleWord(
+            StringBuilder word,
+            AttributedStringBuilder highlightedOutput,
+            State currentState,
+            SyntaxHighlightStyle style) {
+        final String wordStr = word.toString();
+        if (currentState == State.DEFAULT) {
+            if (keywordSet.contains(wordStr.toUpperCase(Locale.ROOT))) {
+                highlightedOutput.style(style.getKeywordStyle());
+            } else {
+                highlightedOutput.style(style.getDefaultStyle());
+            }
+        }
+        highlightedOutput.append(wordStr).style(style.getDefaultStyle());
+        word.setLength(0);
+    }
+
+    /**
+     * State of parser while preparing highlighted output. This class 
represents a state machine.
+     *
+     * <pre>
+     *      MultiLine Comment           Single Line Comment
+     *           |                              |
+     *   (&#47;*,*&#47;) |                              | (--, \n)
+     *           *------------Default-----------*
+     *                        |    |
+     *                        |    |
+     *           *------------*    *------------*
+     *  (&#47;*+,*&#47;) |            |    |            | (', ')
+     *           |            |    |            |
+     *         Hint           |    |          String
+     *                        |    |
+     *                        |    |
+     *           *------------*    *------------*
+     *    (&quot;, &quot;) |                              | (`, `)
+     *           |                              |
+     *     Hive Identifier           Flink Default Identifier
+     * </pre>
+     */
+    private enum State {
+        QUOTED(1, "'", "'", dialect -> true, (asb, style) -> 
asb.style(style.getQuotedStyle())),
+        SQL_QUOTED_IDENTIFIER(
+                2,
+                "`",
+                "`",
+                (dialect) -> dialect == SqlDialect.DEFAULT || dialect == null,
+                (asb, style) -> asb.style(style.getSqlIdentifierStyle())),
+        HIVE_SQL_QUOTED_IDENTIFIER(
+                2,
+                "\"",
+                "\"",
+                (dialect) -> dialect == SqlDialect.HIVE,
+                (asb, style) -> asb.style(style.getSqlIdentifierStyle())),
+        ONE_LINE_COMMENTED(
+                3, "--", "\n", dialect -> true, (asb, style) -> 
asb.style(style.getCommentStyle())),
+        HINTED(4, "/*+", "*/", dialect -> true, (asb, style) -> 
asb.style(style.getHintStyle())),
+        MULTILINE_COMMENTED(
+                5, "/*", "*/", dialect -> true, (asb, style) -> 
asb.style(style.getCommentStyle())),
+        DEFAULT(
+                Integer.MAX_VALUE,
+                null,
+                null,
+                dialect -> true,
+                (asb, style) -> asb.style(style.getDefaultStyle()));
+
+        private final String start;
+        private final String end;
+        private final Function<SqlDialect, Boolean> condition;
+
+        private final int order;
+
+        private final BiConsumer<AttributedStringBuilder, 
SyntaxHighlightStyle> styleSetter;
+
+        private static final List<State> STATE_LIST_WITHOUT_DEFAULT =
+                Arrays.stream(State.values())
+                        .filter(t -> t != DEFAULT)
+                        .sorted(Comparator.comparingInt(o -> o.order))
+                        .collect(Collectors.toList());
+        private static final Set<Character> STATE_START_SYMBOLS =
+                Arrays.stream(State.values())
+                        .filter(t -> t != DEFAULT)
+                        .map(t -> t.start.charAt(0))
+                        .collect(Collectors.toSet());
+
+        State(
+                int order,
+                String start,
+                String end,
+                Function<SqlDialect, Boolean> condition,
+                BiConsumer<AttributedStringBuilder, SyntaxHighlightStyle> 
styleSetter) {
+            this.start = start;
+            this.end = end;
+            this.order = order;
+            this.condition = condition;
+            this.styleSetter = styleSetter;
+        }
+
+        static State computeStateAt(String input, int pos, SqlDialect dialect) 
{
+            final char currentChar = input.charAt(pos);
+            if (!STATE_START_SYMBOLS.contains(currentChar)) {
+                return DEFAULT;
+            }
+            for (State state : STATE_LIST_WITHOUT_DEFAULT) {
+                if (state.condition.apply(dialect)
+                        && state.start.regionMatches(0, input, pos, 
state.start.length())) {
+                    return state;
+                }
+            }
+            return DEFAULT;
+        }
+
+        boolean isEndOfState(String input, int pos) {

Review Comment:
   Add some java doc here to illusture the usage.



##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.client.cli.parser;
+
+import org.apache.flink.table.api.SqlDialect;
+import org.apache.flink.table.api.config.TableConfigOptions;
+import org.apache.flink.table.client.config.SqlClientOptions;
+import org.apache.flink.table.client.gateway.Executor;
+
+import org.jline.reader.LineReader;
+import org.jline.reader.impl.DefaultHighlighter;
+import org.jline.utils.AttributedString;
+import org.jline.utils.AttributedStringBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Properties;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/** Sql Client syntax highlighter. */
+public class SqlClientSyntaxHighlighter extends DefaultHighlighter {
+    private static final Logger LOG = 
LoggerFactory.getLogger(SqlClientSyntaxHighlighter.class);
+    private static Set<String> keywordSet;
+
+    static {
+        try (InputStream is =
+                
SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) {
+            Properties props = new Properties();
+            props.load(is);
+            keywordSet =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("default").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+        } catch (IOException e) {
+            LOG.error("Exception: ", e);
+            keywordSet = Collections.emptySet();
+        }
+    }
+
+    private final Executor executor;
+
+    public SqlClientSyntaxHighlighter(Executor executor) {
+        this.executor = executor;
+    }
+
+    @Override
+    public AttributedString highlight(LineReader reader, String buffer) {
+        final SyntaxHighlightStyle.BuiltInStyle style =
+                SyntaxHighlightStyle.BuiltInStyle.fromString(
+                        executor.getSessionConfig()
+                                
.get(SqlClientOptions.DISPLAY_DEFAULT_COLOR_SCHEMA));
+
+        if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) {
+            return super.highlight(reader, buffer);
+        }
+        final String dialectName =
+                
executor.getSessionConfig().get(TableConfigOptions.TABLE_SQL_DIALECT);
+        final SqlDialect dialect =
+                SqlDialect.HIVE.name().equalsIgnoreCase(dialectName)
+                        ? SqlDialect.HIVE
+                        : SqlDialect.DEFAULT;
+        return getHighlightedOutput(buffer, style.getHighlightStyle(), 
dialect);
+    }
+
+    static AttributedString getHighlightedOutput(
+            String buffer, SyntaxHighlightStyle style, SqlDialect dialect) {
+        final AttributedStringBuilder highlightedOutput = new 
AttributedStringBuilder();
+        State prevParseState = State.DEFAULT;
+        State currentParseState = State.DEFAULT;
+        final StringBuilder word = new StringBuilder();
+        for (int i = 0; i < buffer.length(); i++) {
+            final char currentChar = buffer.charAt(i);
+            if (prevParseState == State.DEFAULT) {
+                currentParseState = State.computeStateAt(buffer, i, dialect);
+                if (currentParseState == State.DEFAULT) {
+                    if (isPartOfWord(currentChar)) {
+                        word.append(currentChar);
+                    } else {
+                        handleWord(word, highlightedOutput, currentParseState, 
style);
+                        highlightedOutput.append(currentChar);
+                        word.setLength(0);
+                    }
+                } else {
+                    handleWord(word, highlightedOutput, State.DEFAULT, style);
+                    currentParseState.styleSetter.accept(highlightedOutput, 
style);
+                    highlightedOutput.append(currentParseState.start);
+                    i += currentParseState.start.length() - 1;
+                }
+            } else {
+                if (currentParseState.isEndOfState(buffer, i)) {
+                    highlightedOutput
+                            .append(word)
+                            .append(currentParseState.end)
+                            .style(style.getDefaultStyle());
+                    word.setLength(0);
+                    i += currentParseState.end.length() - 1;
+                    currentParseState = State.DEFAULT;
+                } else {
+                    word.append(currentChar);
+                }
+            }
+            prevParseState = currentParseState;
+        }
+        handleWord(word, highlightedOutput, currentParseState, style);
+        return highlightedOutput.toAttributedString();
+    }
+
+    private static boolean isPartOfWord(char c) {
+        return Character.isLetterOrDigit(c) || c == '_' || c == '$';
+    }
+
+    private static void handleWord(
+            StringBuilder word,
+            AttributedStringBuilder highlightedOutput,
+            State currentState,
+            SyntaxHighlightStyle style) {
+        final String wordStr = word.toString();
+        if (currentState == State.DEFAULT) {
+            if (keywordSet.contains(wordStr.toUpperCase(Locale.ROOT))) {
+                highlightedOutput.style(style.getKeywordStyle());
+            } else {
+                highlightedOutput.style(style.getDefaultStyle());
+            }
+        }
+        highlightedOutput.append(wordStr).style(style.getDefaultStyle());
+        word.setLength(0);
+    }
+
+    /**
+     * State of parser while preparing highlighted output. This class 
represents a state machine.
+     *
+     * <pre>
+     *      MultiLine Comment           Single Line Comment
+     *           |                              |
+     *   (&#47;*,*&#47;) |                              | (--, \n)
+     *           *------------Default-----------*
+     *                        |    |
+     *                        |    |
+     *           *------------*    *------------*
+     *  (&#47;*+,*&#47;) |            |    |            | (', ')
+     *           |            |    |            |
+     *         Hint           |    |          String
+     *                        |    |
+     *                        |    |
+     *           *------------*    *------------*
+     *    (&quot;, &quot;) |                              | (`, `)
+     *           |                              |
+     *     Hive Identifier           Flink Default Identifier
+     * </pre>
+     */
+    private enum State {
+        QUOTED(1, "'", "'", dialect -> true, (asb, style) -> 
asb.style(style.getQuotedStyle())),
+        SQL_QUOTED_IDENTIFIER(
+                2,
+                "`",
+                "`",
+                (dialect) -> dialect == SqlDialect.DEFAULT || dialect == null,
+                (asb, style) -> asb.style(style.getSqlIdentifierStyle())),
+        HIVE_SQL_QUOTED_IDENTIFIER(
+                2,
+                "\"",
+                "\"",
+                (dialect) -> dialect == SqlDialect.HIVE,
+                (asb, style) -> asb.style(style.getSqlIdentifierStyle())),
+        ONE_LINE_COMMENTED(
+                3, "--", "\n", dialect -> true, (asb, style) -> 
asb.style(style.getCommentStyle())),
+        HINTED(4, "/*+", "*/", dialect -> true, (asb, style) -> 
asb.style(style.getHintStyle())),
+        MULTILINE_COMMENTED(
+                5, "/*", "*/", dialect -> true, (asb, style) -> 
asb.style(style.getCommentStyle())),
+        DEFAULT(
+                Integer.MAX_VALUE,
+                null,
+                null,
+                dialect -> true,
+                (asb, style) -> asb.style(style.getDefaultStyle()));
+
+        private final String start;
+        private final String end;
+        private final Function<SqlDialect, Boolean> condition;
+
+        private final int order;
+
+        private final BiConsumer<AttributedStringBuilder, 
SyntaxHighlightStyle> styleSetter;
+
+        private static final List<State> STATE_LIST_WITHOUT_DEFAULT =
+                Arrays.stream(State.values())
+                        .filter(t -> t != DEFAULT)
+                        .sorted(Comparator.comparingInt(o -> o.order))
+                        .collect(Collectors.toList());
+        private static final Set<Character> STATE_START_SYMBOLS =
+                Arrays.stream(State.values())
+                        .filter(t -> t != DEFAULT)
+                        .map(t -> t.start.charAt(0))
+                        .collect(Collectors.toSet());
+
+        State(
+                int order,
+                String start,
+                String end,
+                Function<SqlDialect, Boolean> condition,
+                BiConsumer<AttributedStringBuilder, SyntaxHighlightStyle> 
styleSetter) {
+            this.start = start;
+            this.end = end;
+            this.order = order;
+            this.condition = condition;
+            this.styleSetter = styleSetter;
+        }
+
+        static State computeStateAt(String input, int pos, SqlDialect dialect) 
{
+            final char currentChar = input.charAt(pos);
+            if (!STATE_START_SYMBOLS.contains(currentChar)) {
+                return DEFAULT;
+            }
+            for (State state : STATE_LIST_WITHOUT_DEFAULT) {
+                if (state.condition.apply(dialect)
+                        && state.start.regionMatches(0, input, pos, 
state.start.length())) {
+                    return state;
+                }
+            }
+            return DEFAULT;
+        }
+
+        boolean isEndOfState(String input, int pos) {
+            if (this == DEFAULT) {
+                return false;
+            }

Review Comment:
   nit: BTW, it's not correct here because the other state's beginning is the 
end of the current state. Or do we just throw an exception to notify others not 
to use this for the `DEFAULT` state?



##########
flink-table/flink-sql-client/src/main/resources/keywords.properties:
##########
@@ -0,0 +1,20 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to you under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Resources for the Apache Calcite project.
+# See wrapper class org.apache.calcite.runtime.CalciteResource.
+#
+default=ABS;ALL;ALLOCATE;ALLOW;ALTER;AND;ANY;ARE;ARRAY;ARRAY_AGG;ARRAY_CONCAT_AGG;ARRAY_MAX_CARDINALITY;AS;ASENSITIVE;ASYMMETRIC;AT;ATOMIC;AUTHORIZATION;AVG;BEGIN;BEGIN_FRAME;BEGIN_PARTITION;BETWEEN;BIGINT;BINARY;BIT;BLOB;BOOLEAN;BOTH;BY;BYTES;CALL;CALLED;CARDINALITY;CASCADED;CASE;CAST;CATALOGS;CEIL;CEILING;CHAR;CHARACTER;CHARACTER_LENGTH;CHAR_LENGTH;CHECK;CLASSIFIER;CLOB;CLOSE;COALESCE;COLLATE;COLLECT;COLUMN;COMMENT;COMMIT;CONDITION;CONNECT;CONSTRAINT;CONTAINS;CONVERT;CORR;CORRESPONDING;COUNT;COVAR_POP;COVAR_SAMP;CREATE;CROSS;CUBE;CUME_DIST;CURRENT;CURRENT_CATALOG;CURRENT_DATE;CURRENT_DEFAULT_TRANSFORM_GROUP;CURRENT_PATH;CURRENT_ROLE;CURRENT_ROW;CURRENT_SCHEMA;CURRENT_TIME;CURRENT_TIMESTAMP;CURRENT_TRANSFORM_GROUP_FOR_TYPE;CURRENT_USER;CURSOR;CYCLE;DATABASES;DATE;DAY;DEALLOCATE;DEC;DECIMAL;DECLARE;DEFAULT;DEFINE;DELETE;DENSE_RANK;DEREF;DESCRIBE;DETERMINISTIC;DISALLOW;DISCONNECT;DISTINCT;DOT;DOUBLE;DROP;DYNAMIC;EACH;ELEMENT;ELSE;EMPTY;END;END-EXEC;END_FRAME;END_PARTITION;EQUALS;ESCA
 
PE;EVERY;EXCEPT;EXEC;EXECUTE;EXISTS;EXP;EXPLAIN;EXTEND;EXTENDED;EXTERNAL;EXTRACT;FALSE;FETCH;FILTER;FIRST_VALUE;FLOAT;FLOOR;FOR;FOREIGN;FRAME_ROW;FREE;FROM;FULL;FUNCTION;FUNCTIONS;FUSION;GET;GLOBAL;GRANT;GROUP;GROUPING;GROUPS;GROUP_CONCAT;HAVING;HOLD;HOUR;IDENTITY;ILIKE;IMPORT;IN;INCLUDE;INDICATOR;INITIAL;INNER;INOUT;INSENSITIVE;INSERT;INT;INTEGER;INTERSECT;INTERSECTION;INTERVAL;INTO;IS;JOIN;JSON_ARRAY;JSON_ARRAYAGG;JSON_EXISTS;JSON_OBJECT;JSON_OBJECTAGG;JSON_QUERY;JSON_VALUE;LAG;LANGUAGE;LARGE;LAST_VALUE;LATERAL;LEAD;LEADING;LEFT;LIKE;LIKE_REGEX;LIMIT;LN;LOCAL;LOCALTIME;LOCALTIMESTAMP;LOWER;MATCH;MATCHES;MATCH_NUMBER;MATCH_RECOGNIZE;MAX;MEASURES;MEMBER;MERGE;METHOD;MIN;MINUS;MINUTE;MOD;MODIFIES;MODIFY;MODULE;MODULES;MONTH;MULTISET;NATIONAL;NATURAL;NCHAR;NCLOB;NEW;NEXT;NO;NONE;NORMALIZE;NOT;NTH_VALUE;NTILE;NULL;NULLIF;NUMERIC;OCCURRENCES_REGEX;OCTET_LENGTH;OF;OFFSET;OLD;OMIT;ON;ONE;ONLY;OPEN;OR;ORDER;OUT;OUTER;OVER;OVERLAPS;OVERLAY;PARAMETER;PARTITION;PATTERN;PER;PERCENT;PERCENTILE_
 
CONT;PERCENTILE_DISC;PERCENT_RANK;PERIOD;PERMUTE;PIVOT;PORTION;POSITION;POSITION_REGEX;POWER;PRECEDES;PRECISION;PREPARE;PREV;PRIMARY;PROCEDURE;RANGE;RANK;RAW;READS;REAL;RECURSIVE;REF;REFERENCES;REFERENCING;REGR_AVGX;REGR_AVGY;REGR_COUNT;REGR_INTERCEPT;REGR_R2;REGR_SLOPE;REGR_SXX;REGR_SXY;REGR_SYY;RELEASE;RENAME;RESET;RESULT;RETURN;RETURNS;REVOKE;RIGHT;RLIKE;ROLLBACK;ROLLUP;ROW;ROWS;ROW_NUMBER;RUNNING;SAVEPOINT;SCALA;SCOPE;SCROLL;SEARCH;SECOND;SEEK;SELECT;SENSITIVE;SEPARATOR;SESSION_USER;SET;SHOW;SIMILAR;SKIP;SMALLINT;SOME;SPECIFIC;SPECIFICTYPE;SQL;SQLEXCEPTION;SQLSTATE;SQLWARNING;SQRT;START;STATEMENT;STATIC;STDDEV_POP;STDDEV_SAMP;STREAM;STRING;STRING_AGG;SUBMULTISET;SUBSET;SUBSTRING;SUBSTRING_REGEX;SUCCEEDS;SUM;SYMMETRIC;SYSTEM;SYSTEM_TIME;SYSTEM_USER;TABLE;TABLES;TABLESAMPLE;THEN;TIME;TIMESTAMP;TIMESTAMP_LTZ;TIMEZONE_HOUR;TIMEZONE_MINUTE;TINYINT;TO;TRAILING;TRANSLATE;TRANSLATE_REGEX;TRANSLATION;TREAT;TRIGGER;TRIM;TRIM_ARRAY;TRUE;TRUNCATE;UESCAPE;UNION;UNIQUE;UNKNOWN;UNNEST;UNPIVOT;
 
UPDATE;UPPER;UPSERT;USE;USER;USING;VALUE;VALUES;VALUE_OF;VARBINARY;VARCHAR;VARYING;VAR_POP;VAR_SAMP;VERSIONING;VIEWS;WATERMARK;WATERMARKS;WHEN;WHENEVER;WHERE;WIDTH_BUCKET;WINDOW;WITH;WITHIN;WITHOUT;YEAR

Review Comment:
   I think it's better we can use reflection to get these keywords. For 
example, we can do like this:
   
   ```
    try {
               Field reservedWords =
                       
SqlAbstractParserImpl.MetadataImpl.class.getDeclaredField("reservedWords");
               reservedWords.setAccessible(true);
               return (Set<String>)
                       reservedWords.get(
                               FlinkSqlParserImpl.FACTORY
                                       .getParser(new StringReader(""))
                                       .getMetadata());
           } catch (Throwable t) {
               // ignore
               LOG.warn("Can not get reserved keywords.", t)
               return Collections.emptySet();
           }
   ```
   
   Does calcite has plan to open a ticket to allow others to fetch these?
   



##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.client.cli.parser;
+
+import org.apache.flink.table.api.SqlDialect;
+import org.apache.flink.table.api.config.TableConfigOptions;
+import org.apache.flink.table.client.config.SqlClientOptions;
+import org.apache.flink.table.client.gateway.Executor;
+
+import org.jline.reader.LineReader;
+import org.jline.reader.impl.DefaultHighlighter;
+import org.jline.utils.AttributedString;
+import org.jline.utils.AttributedStringBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Properties;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/** Sql Client syntax highlighter. */
+public class SqlClientSyntaxHighlighter extends DefaultHighlighter {
+    private static final Logger LOG = 
LoggerFactory.getLogger(SqlClientSyntaxHighlighter.class);
+    private static Set<String> keywordSet;

Review Comment:
   nit: keywordSet -> keywords



##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/config/SqlClientOptions.java:
##########
@@ -68,4 +69,12 @@ private SqlClientOptions() {}
                             "Deprecated, please use 
table.display.max-column-width instead. When printing the query results, this 
parameter determines the number of characters shown on screen before 
truncating. "
                                     + "This only applies to columns with 
variable-length types (e.g. STRING) in streaming mode. "
                                     + "Fixed-length types and all types in 
batch mode are printed using a deterministic column width.");
+
+    @Documentation.TableOption(execMode = 
Documentation.ExecMode.BATCH_STREAMING)
+    public static final ConfigOption<String> DISPLAY_DEFAULT_COLOR_SCHEMA =
+            ConfigOptions.key("sql-client.display.default-color-schema")

Review Comment:
   How about `sql-client.display.color-schema`?



##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.client.cli.parser;
+
+import org.apache.flink.table.api.SqlDialect;
+import org.apache.flink.table.api.config.TableConfigOptions;
+import org.apache.flink.table.client.config.SqlClientOptions;
+import org.apache.flink.table.client.gateway.Executor;
+
+import org.jline.reader.LineReader;
+import org.jline.reader.impl.DefaultHighlighter;
+import org.jline.utils.AttributedString;
+import org.jline.utils.AttributedStringBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Properties;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/** Sql Client syntax highlighter. */
+public class SqlClientSyntaxHighlighter extends DefaultHighlighter {
+    private static final Logger LOG = 
LoggerFactory.getLogger(SqlClientSyntaxHighlighter.class);
+    private static Set<String> keywordSet;
+
+    static {
+        try (InputStream is =
+                
SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) {
+            Properties props = new Properties();
+            props.load(is);
+            keywordSet =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("default").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+        } catch (IOException e) {
+            LOG.error("Exception: ", e);
+            keywordSet = Collections.emptySet();
+        }
+    }
+
+    private final Executor executor;
+
+    public SqlClientSyntaxHighlighter(Executor executor) {
+        this.executor = executor;
+    }
+
+    @Override
+    public AttributedString highlight(LineReader reader, String buffer) {
+        final SyntaxHighlightStyle.BuiltInStyle style =
+                SyntaxHighlightStyle.BuiltInStyle.fromString(
+                        executor.getSessionConfig()
+                                
.get(SqlClientOptions.DISPLAY_DEFAULT_COLOR_SCHEMA));
+
+        if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) {
+            return super.highlight(reader, buffer);
+        }
+        final String dialectName =
+                
executor.getSessionConfig().get(TableConfigOptions.TABLE_SQL_DIALECT);
+        final SqlDialect dialect =
+                SqlDialect.HIVE.name().equalsIgnoreCase(dialectName)
+                        ? SqlDialect.HIVE
+                        : SqlDialect.DEFAULT;
+        return getHighlightedOutput(buffer, style.getHighlightStyle(), 
dialect);
+    }
+
+    static AttributedString getHighlightedOutput(
+            String buffer, SyntaxHighlightStyle style, SqlDialect dialect) {
+        final AttributedStringBuilder highlightedOutput = new 
AttributedStringBuilder();
+        State prevParseState = State.DEFAULT;
+        State currentParseState = State.DEFAULT;
+        final StringBuilder word = new StringBuilder();
+        for (int i = 0; i < buffer.length(); i++) {
+            final char currentChar = buffer.charAt(i);
+            if (prevParseState == State.DEFAULT) {
+                currentParseState = State.computeStateAt(buffer, i, dialect);
+                if (currentParseState == State.DEFAULT) {
+                    if (isPartOfWord(currentChar)) {
+                        word.append(currentChar);
+                    } else {
+                        handleWord(word, highlightedOutput, currentParseState, 
style);
+                        highlightedOutput.append(currentChar);
+                        word.setLength(0);
+                    }
+                } else {
+                    handleWord(word, highlightedOutput, State.DEFAULT, style);
+                    currentParseState.styleSetter.accept(highlightedOutput, 
style);
+                    highlightedOutput.append(currentParseState.start);
+                    i += currentParseState.start.length() - 1;
+                }
+            } else {
+                if (currentParseState.isEndOfState(buffer, i)) {
+                    highlightedOutput
+                            .append(word)
+                            .append(currentParseState.end)
+                            .style(style.getDefaultStyle());
+                    word.setLength(0);
+                    i += currentParseState.end.length() - 1;
+                    currentParseState = State.DEFAULT;
+                } else {
+                    word.append(currentChar);
+                }
+            }
+            prevParseState = currentParseState;
+        }
+        handleWord(word, highlightedOutput, currentParseState, style);
+        return highlightedOutput.toAttributedString();
+    }
+
+    private static boolean isPartOfWord(char c) {
+        return Character.isLetterOrDigit(c) || c == '_' || c == '$';
+    }
+
+    private static void handleWord(
+            StringBuilder word,
+            AttributedStringBuilder highlightedOutput,
+            State currentState,
+            SyntaxHighlightStyle style) {
+        final String wordStr = word.toString();
+        if (currentState == State.DEFAULT) {
+            if (keywordSet.contains(wordStr.toUpperCase(Locale.ROOT))) {
+                highlightedOutput.style(style.getKeywordStyle());
+            } else {
+                highlightedOutput.style(style.getDefaultStyle());
+            }
+        }
+        highlightedOutput.append(wordStr).style(style.getDefaultStyle());
+        word.setLength(0);
+    }
+
+    /**
+     * State of parser while preparing highlighted output. This class 
represents a state machine.
+     *
+     * <pre>
+     *      MultiLine Comment           Single Line Comment
+     *           |                              |
+     *   (&#47;*,*&#47;) |                              | (--, \n)
+     *           *------------Default-----------*
+     *                        |    |
+     *                        |    |
+     *           *------------*    *------------*
+     *  (&#47;*+,*&#47;) |            |    |            | (', ')
+     *           |            |    |            |
+     *         Hint           |    |          String
+     *                        |    |
+     *                        |    |
+     *           *------------*    *------------*
+     *    (&quot;, &quot;) |                              | (`, `)
+     *           |                              |
+     *     Hive Identifier           Flink Default Identifier
+     * </pre>
+     */
+    private enum State {
+        QUOTED(1, "'", "'", dialect -> true, (asb, style) -> 
asb.style(style.getQuotedStyle())),
+        SQL_QUOTED_IDENTIFIER(
+                2,
+                "`",
+                "`",
+                (dialect) -> dialect == SqlDialect.DEFAULT || dialect == null,
+                (asb, style) -> asb.style(style.getSqlIdentifierStyle())),
+        HIVE_SQL_QUOTED_IDENTIFIER(
+                2,
+                "\"",
+                "\"",
+                (dialect) -> dialect == SqlDialect.HIVE,
+                (asb, style) -> asb.style(style.getSqlIdentifierStyle())),
+        ONE_LINE_COMMENTED(
+                3, "--", "\n", dialect -> true, (asb, style) -> 
asb.style(style.getCommentStyle())),
+        HINTED(4, "/*+", "*/", dialect -> true, (asb, style) -> 
asb.style(style.getHintStyle())),
+        MULTILINE_COMMENTED(
+                5, "/*", "*/", dialect -> true, (asb, style) -> 
asb.style(style.getCommentStyle())),
+        DEFAULT(
+                Integer.MAX_VALUE,
+                null,
+                null,
+                dialect -> true,
+                (asb, style) -> asb.style(style.getDefaultStyle()));
+
+        private final String start;
+        private final String end;
+        private final Function<SqlDialect, Boolean> condition;
+
+        private final int order;
+
+        private final BiConsumer<AttributedStringBuilder, 
SyntaxHighlightStyle> styleSetter;
+
+        private static final List<State> STATE_LIST_WITHOUT_DEFAULT =
+                Arrays.stream(State.values())
+                        .filter(t -> t != DEFAULT)
+                        .sorted(Comparator.comparingInt(o -> o.order))
+                        .collect(Collectors.toList());
+        private static final Set<Character> STATE_START_SYMBOLS =
+                Arrays.stream(State.values())
+                        .filter(t -> t != DEFAULT)
+                        .map(t -> t.start.charAt(0))
+                        .collect(Collectors.toSet());
+
+        State(
+                int order,

Review Comment:
   nit: I think we don't need to specify order here. Because State.values() 
always return values as the specified order.
   
   [1] 
https://stackoverflow.com/questions/11898900/will-the-order-for-enum-values-always-same



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to