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


##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java:
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.gateway.Executor;
+
+import org.jline.reader.LineReader;
+import org.jline.reader.impl.DefaultHighlighter;
+import org.jline.utils.AttributedString;
+import org.jline.utils.AttributedStringBuilder;
+
+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;
+
+import static org.apache.flink.table.client.cli.CliClient.COLOR_SCHEMA_VAR;
+
+/** Sql Client syntax highlighter. */
+public class SqlClientSyntaxHighlighter extends DefaultHighlighter {
+    private static final Set<String> FLINK_KEYWORD_SET;
+    private static final Set<String> HIVE_KEYWORD_SET;
+
+    static {
+        try (InputStream is =
+                
SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) {
+            Properties props = new Properties();
+            props.load(is);
+            FLINK_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("default").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+            HIVE_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("hive").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+        } catch (IOException e) {
+            throw new RuntimeException(e);

Review Comment:
   Can we just log the exception here? The syntax highlighting should not 
influence the main logic in the sql client. WDYT?



##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java:
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.gateway.Executor;
+
+import org.jline.reader.LineReader;
+import org.jline.reader.impl.DefaultHighlighter;
+import org.jline.utils.AttributedString;
+import org.jline.utils.AttributedStringBuilder;
+
+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;
+
+import static org.apache.flink.table.client.cli.CliClient.COLOR_SCHEMA_VAR;
+
+/** Sql Client syntax highlighter. */
+public class SqlClientSyntaxHighlighter extends DefaultHighlighter {
+    private static final Set<String> FLINK_KEYWORD_SET;
+    private static final Set<String> HIVE_KEYWORD_SET;
+
+    static {
+        try (InputStream is =
+                
SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) {
+            Properties props = new Properties();
+            props.load(is);
+            FLINK_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("default").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+            HIVE_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("hive").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private final Executor executor;
+
+    public SqlClientSyntaxHighlighter(Executor executor) {
+        this.executor = executor;
+    }
+
+    @Override
+    public AttributedString highlight(LineReader reader, String buffer) {
+
+        final Object colorSchemeOrdinal = reader.getVariable(COLOR_SCHEMA_VAR);
+        SyntaxHighlightStyle.BuiltInStyle style =
+                SyntaxHighlightStyle.BuiltInStyle.fromOrdinal(
+                        colorSchemeOrdinal == null ? 0 : (Integer) 
colorSchemeOrdinal);
+        if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) {
+            return super.highlight(reader, buffer);
+        }
+        final SqlDialect dialect =
+                executor.getSessionConfig()
+                                .get(TableConfigOptions.TABLE_SQL_DIALECT)
+                                .equalsIgnoreCase(SqlDialect.HIVE.toString())

Review Comment:
   ```
   final SqlDialect dialect =
                   executor.getSessionConfig()
                                   .get(TableConfigOptions.TABLE_SQL_DIALECT)
   ```



##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java:
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.gateway.Executor;
+
+import org.jline.reader.LineReader;
+import org.jline.reader.impl.DefaultHighlighter;
+import org.jline.utils.AttributedString;
+import org.jline.utils.AttributedStringBuilder;
+
+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;
+
+import static org.apache.flink.table.client.cli.CliClient.COLOR_SCHEMA_VAR;
+
+/** Sql Client syntax highlighter. */
+public class SqlClientSyntaxHighlighter extends DefaultHighlighter {
+    private static final Set<String> FLINK_KEYWORD_SET;
+    private static final Set<String> HIVE_KEYWORD_SET;
+
+    static {
+        try (InputStream is =
+                
SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) {
+            Properties props = new Properties();
+            props.load(is);
+            FLINK_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("default").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+            HIVE_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("hive").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private final Executor executor;
+
+    public SqlClientSyntaxHighlighter(Executor executor) {
+        this.executor = executor;
+    }
+
+    @Override
+    public AttributedString highlight(LineReader reader, String buffer) {
+

Review Comment:
   nit: remove this empty line



##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/CliClient.java:
##########
@@ -307,6 +314,26 @@ private LineReader createLineReader(Terminal terminal, 
ExecutionMode mode) {
             terminal.writer().println(msg);
             LOG.warn(msg);
         }
+        if (mode == ExecutionMode.INTERACTIVE_EXECUTION) {
+            lineReader.setVariable(
+                    COLOR_SCHEMA_VAR,
+                    executor.getSessionConfig()

Review Comment:
   It seems we can only set this value when start the client. I can not change 
the value using `SET` command.



##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/CliClient.java:
##########
@@ -307,6 +314,26 @@ private LineReader createLineReader(Terminal terminal, 
ExecutionMode mode) {
             terminal.writer().println(msg);
             LOG.warn(msg);
         }
+        if (mode == ExecutionMode.INTERACTIVE_EXECUTION) {
+            lineReader.setVariable(
+                    COLOR_SCHEMA_VAR,
+                    executor.getSessionConfig()
+                            .get(SqlClientOptions.DISPLAY_DEFAULT_COLOR_SCHEMA)
+                            .ordinal());
+            final Widget widget =
+                    () -> {
+                        final Object colorSchemeOrdinal = 
lineReader.getVariable(COLOR_SCHEMA_VAR);
+                        int ord = colorSchemeOrdinal == null ? 0 : (Integer) 
colorSchemeOrdinal;
+                        lineReader.setVariable(
+                                COLOR_SCHEMA_VAR,
+                                (ord + 1) % 
SyntaxHighlightStyle.BuiltInStyle.values().length);
+                        return false;
+                    };
+            lineReader.getWidgets().put(COLOR_SCHEMA_VAR, widget);
+            final CharSequence keySeq = alt('h');
+            lineReader.getKeyMaps().get(LineReader.EMACS).bind(widget, keySeq);
+            lineReader.getKeyMaps().get(LineReader.VIINS).bind(widget, keySeq);
+        }

Review Comment:
   I don't reproduce this in my terminal... I just press ESC+h, nothing 
happens...
   
   BTW, I don't think it's a good idea to use shortcuts because some people may 
change their key mapping.



##########
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:
   How do you get the list? Do you just copy from the jj file?



##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java:
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.gateway.Executor;
+
+import org.jline.reader.LineReader;
+import org.jline.reader.impl.DefaultHighlighter;
+import org.jline.utils.AttributedString;
+import org.jline.utils.AttributedStringBuilder;
+
+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;
+
+import static org.apache.flink.table.client.cli.CliClient.COLOR_SCHEMA_VAR;
+
+/** Sql Client syntax highlighter. */
+public class SqlClientSyntaxHighlighter extends DefaultHighlighter {
+    private static final Set<String> FLINK_KEYWORD_SET;
+    private static final Set<String> HIVE_KEYWORD_SET;
+
+    static {
+        try (InputStream is =
+                
SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) {
+            Properties props = new Properties();
+            props.load(is);
+            FLINK_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("default").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+            HIVE_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("hive").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private final Executor executor;
+
+    public SqlClientSyntaxHighlighter(Executor executor) {
+        this.executor = executor;
+    }
+
+    @Override
+    public AttributedString highlight(LineReader reader, String buffer) {
+
+        final Object colorSchemeOrdinal = reader.getVariable(COLOR_SCHEMA_VAR);
+        SyntaxHighlightStyle.BuiltInStyle style =
+                SyntaxHighlightStyle.BuiltInStyle.fromOrdinal(
+                        colorSchemeOrdinal == null ? 0 : (Integer) 
colorSchemeOrdinal);
+        if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) {
+            return super.highlight(reader, buffer);
+        }
+        final SqlDialect dialect =
+                executor.getSessionConfig()
+                                .get(TableConfigOptions.TABLE_SQL_DIALECT)
+                                .equalsIgnoreCase(SqlDialect.HIVE.toString())
+                        ? SqlDialect.HIVE
+                        : SqlDialect.DEFAULT;
+        return getHighlightedOutput(buffer, style.getHighlightStyle(), 
dialect);
+    }
+
+    static AttributedString getHighlightedOutput(
+            String buffer, SyntaxHighlightStyle style, SqlDialect dialect) {
+        final Set<Character> stateStartSymbols =
+                Arrays.stream(State.values())
+                        .map(t -> t.getStart(dialect).charAt(0))
+                        .collect(Collectors.toSet());
+        final AttributedStringBuilder highlightedOutput = new 
AttributedStringBuilder();
+        State currentParseState = null;
+        int counter = 0;
+        StringBuilder word = new StringBuilder();
+        for (int i = 0; i < buffer.length(); i++) {
+            final char c = buffer.charAt(i);
+            if (currentParseState == null) {
+                if (stateStartSymbols.contains(c)) {

Review Comment:
   What happens if users wants to escape some character?



##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java:
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.gateway.Executor;
+
+import org.jline.reader.LineReader;
+import org.jline.reader.impl.DefaultHighlighter;
+import org.jline.utils.AttributedString;
+import org.jline.utils.AttributedStringBuilder;
+
+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;
+
+import static org.apache.flink.table.client.cli.CliClient.COLOR_SCHEMA_VAR;
+
+/** Sql Client syntax highlighter. */
+public class SqlClientSyntaxHighlighter extends DefaultHighlighter {
+    private static final Set<String> FLINK_KEYWORD_SET;
+    private static final Set<String> HIVE_KEYWORD_SET;
+
+    static {
+        try (InputStream is =
+                
SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) {
+            Properties props = new Properties();
+            props.load(is);
+            FLINK_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("default").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+            HIVE_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("hive").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private final Executor executor;
+
+    public SqlClientSyntaxHighlighter(Executor executor) {
+        this.executor = executor;
+    }
+
+    @Override
+    public AttributedString highlight(LineReader reader, String buffer) {
+
+        final Object colorSchemeOrdinal = reader.getVariable(COLOR_SCHEMA_VAR);
+        SyntaxHighlightStyle.BuiltInStyle style =
+                SyntaxHighlightStyle.BuiltInStyle.fromOrdinal(
+                        colorSchemeOrdinal == null ? 0 : (Integer) 
colorSchemeOrdinal);
+        if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) {
+            return super.highlight(reader, buffer);
+        }
+        final SqlDialect dialect =
+                executor.getSessionConfig()
+                                .get(TableConfigOptions.TABLE_SQL_DIALECT)
+                                .equalsIgnoreCase(SqlDialect.HIVE.toString())
+                        ? SqlDialect.HIVE
+                        : SqlDialect.DEFAULT;
+        return getHighlightedOutput(buffer, style.getHighlightStyle(), 
dialect);
+    }
+
+    static AttributedString getHighlightedOutput(
+            String buffer, SyntaxHighlightStyle style, SqlDialect dialect) {
+        final Set<Character> stateStartSymbols =
+                Arrays.stream(State.values())
+                        .map(t -> t.getStart(dialect).charAt(0))
+                        .collect(Collectors.toSet());
+        final AttributedStringBuilder highlightedOutput = new 
AttributedStringBuilder();
+        State currentParseState = null;
+        int counter = 0;
+        StringBuilder word = new StringBuilder();
+        for (int i = 0; i < buffer.length(); i++) {
+            final char c = buffer.charAt(i);
+            if (currentParseState == null) {
+                if (stateStartSymbols.contains(c)) {
+                    for (State s : State.STATE_LIST) {
+                        final String stateStart = s.getStart(dialect);
+                        if (buffer.regionMatches(i, stateStart, 0, 
stateStart.length())) {
+                            handleWord(
+                                    word,
+                                    highlightedOutput,
+                                    currentParseState,
+                                    style,
+                                    true,
+                                    dialect);
+                            s.getConsumer().accept(highlightedOutput, style);
+                            highlightedOutput.append(stateStart);
+                            counter++;
+                            currentParseState = s;
+                            i += stateStart.length() - 1;
+                            break;
+                        }
+                    }
+                }
+                if (currentParseState == null) {
+                    if (!Character.isLetter(c) && !Character.isDigit(c) && c 
!= '_') {
+                        handleWord(
+                                word, highlightedOutput, currentParseState, 
style, true, dialect);
+                        highlightedOutput.append(c);
+                    } else {
+                        word.append(c);
+                    }
+                }
+            } else {
+                word.append(c);
+                final String stateEnd = currentParseState.getEnd(dialect);
+                if (buffer.regionMatches(i, stateEnd, 0, stateEnd.length())) {
+                    counter--;
+                    if (counter == 0) {
+                        handleWord(
+                                word, highlightedOutput, currentParseState, 
style, true, dialect);
+                        i += stateEnd.length() - 1;
+                        currentParseState = null;
+                    }
+                }
+            }
+        }
+        handleWord(word, highlightedOutput, currentParseState, style, false, 
dialect);
+        return highlightedOutput.toAttributedString();
+    }
+
+    private static void handleWord(
+            StringBuilder word,
+            AttributedStringBuilder sb,
+            State currentState,
+            SyntaxHighlightStyle style,
+            boolean turnOffHighlight,
+            SqlDialect dialect) {
+        final String wordStr = word.toString();
+        if (currentState == null) {
+            final Set<String> keyWordSet =
+                    dialect == SqlDialect.HIVE ? HIVE_KEYWORD_SET : 
FLINK_KEYWORD_SET;
+            if (keyWordSet.contains(wordStr.toUpperCase(Locale.ROOT))) {
+                sb.style(style.getKeywordStyle());
+            } else {
+                sb.style(style.getDefaultStyle());
+            }
+            sb.append(wordStr);
+        } else if (turnOffHighlight) {
+            sb.append(wordStr);
+            final String stateEnd = currentState.getEnd(dialect);
+            if (stateEnd.length() > 1) {
+                sb.append(stateEnd.substring(1));
+            }
+        } else {
+            sb.append(wordStr);
+        }
+        word.setLength(0);
+        sb.style(style.getDefaultStyle());
+    }
+
+    /** State of parser while preparing highlighted output. */

Review Comment:
   Add some description like this 
   
   ```
   
   /**
    * This class represents a state machine.
    *
    * <pre>
    *      MultiLine Comment                Single Line Comment
    *           |                                   |
    *   (&#47;*,*&#47;) |                                   | (--, \n)
    *           *------------Default----------------*
    *                        |    |
    *                        |    |
    *           *------------*    *------------------*
    *    (`, `) |                                   |(', ')
    *           |                                   |
    *         Identifier                          String
    *
    * </pre>
    */
   ```



##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java:
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.gateway.Executor;
+
+import org.jline.reader.LineReader;
+import org.jline.reader.impl.DefaultHighlighter;
+import org.jline.utils.AttributedString;
+import org.jline.utils.AttributedStringBuilder;
+
+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;
+
+import static org.apache.flink.table.client.cli.CliClient.COLOR_SCHEMA_VAR;
+
+/** Sql Client syntax highlighter. */
+public class SqlClientSyntaxHighlighter extends DefaultHighlighter {
+    private static final Set<String> FLINK_KEYWORD_SET;
+    private static final Set<String> HIVE_KEYWORD_SET;
+
+    static {
+        try (InputStream is =
+                
SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) {
+            Properties props = new Properties();
+            props.load(is);
+            FLINK_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("default").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+            HIVE_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("hive").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private final Executor executor;
+
+    public SqlClientSyntaxHighlighter(Executor executor) {
+        this.executor = executor;
+    }
+
+    @Override
+    public AttributedString highlight(LineReader reader, String buffer) {
+
+        final Object colorSchemeOrdinal = reader.getVariable(COLOR_SCHEMA_VAR);
+        SyntaxHighlightStyle.BuiltInStyle style =
+                SyntaxHighlightStyle.BuiltInStyle.fromOrdinal(
+                        colorSchemeOrdinal == null ? 0 : (Integer) 
colorSchemeOrdinal);
+        if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) {
+            return super.highlight(reader, buffer);
+        }
+        final SqlDialect dialect =
+                executor.getSessionConfig()
+                                .get(TableConfigOptions.TABLE_SQL_DIALECT)
+                                .equalsIgnoreCase(SqlDialect.HIVE.toString())
+                        ? SqlDialect.HIVE
+                        : SqlDialect.DEFAULT;
+        return getHighlightedOutput(buffer, style.getHighlightStyle(), 
dialect);
+    }
+
+    static AttributedString getHighlightedOutput(
+            String buffer, SyntaxHighlightStyle style, SqlDialect dialect) {
+        final Set<Character> stateStartSymbols =
+                Arrays.stream(State.values())
+                        .map(t -> t.getStart(dialect).charAt(0))
+                        .collect(Collectors.toSet());
+        final AttributedStringBuilder highlightedOutput = new 
AttributedStringBuilder();
+        State currentParseState = null;
+        int counter = 0;
+        StringBuilder word = new StringBuilder();
+        for (int i = 0; i < buffer.length(); i++) {
+            final char c = buffer.charAt(i);
+            if (currentParseState == null) {
+                if (stateStartSymbols.contains(c)) {
+                    for (State s : State.STATE_LIST) {
+                        final String stateStart = s.getStart(dialect);
+                        if (buffer.regionMatches(i, stateStart, 0, 
stateStart.length())) {
+                            handleWord(
+                                    word,
+                                    highlightedOutput,
+                                    currentParseState,
+                                    style,
+                                    true,
+                                    dialect);
+                            s.getConsumer().accept(highlightedOutput, style);
+                            highlightedOutput.append(stateStart);
+                            counter++;
+                            currentParseState = s;
+                            i += stateStart.length() - 1;
+                            break;
+                        }
+                    }
+                }
+                if (currentParseState == null) {
+                    if (!Character.isLetter(c) && !Character.isDigit(c) && c 
!= '_') {
+                        handleWord(
+                                word, highlightedOutput, currentParseState, 
style, true, dialect);
+                        highlightedOutput.append(c);
+                    } else {
+                        word.append(c);
+                    }
+                }
+            } else {
+                word.append(c);
+                final String stateEnd = currentParseState.getEnd(dialect);
+                if (buffer.regionMatches(i, stateEnd, 0, stateEnd.length())) {
+                    counter--;
+                    if (counter == 0) {
+                        handleWord(
+                                word, highlightedOutput, currentParseState, 
style, true, dialect);
+                        i += stateEnd.length() - 1;
+                        currentParseState = null;
+                    }
+                }
+            }
+        }
+        handleWord(word, highlightedOutput, currentParseState, style, false, 
dialect);
+        return highlightedOutput.toAttributedString();
+    }
+
+    private static void handleWord(
+            StringBuilder word,
+            AttributedStringBuilder sb,
+            State currentState,
+            SyntaxHighlightStyle style,
+            boolean turnOffHighlight,
+            SqlDialect dialect) {
+        final String wordStr = word.toString();
+        if (currentState == null) {
+            final Set<String> keyWordSet =
+                    dialect == SqlDialect.HIVE ? HIVE_KEYWORD_SET : 
FLINK_KEYWORD_SET;
+            if (keyWordSet.contains(wordStr.toUpperCase(Locale.ROOT))) {
+                sb.style(style.getKeywordStyle());
+            } else {
+                sb.style(style.getDefaultStyle());
+            }
+            sb.append(wordStr);
+        } else if (turnOffHighlight) {
+            sb.append(wordStr);
+            final String stateEnd = currentState.getEnd(dialect);
+            if (stateEnd.length() > 1) {
+                sb.append(stateEnd.substring(1));
+            }
+        } else {
+            sb.append(wordStr);
+        }
+        word.setLength(0);
+        sb.style(style.getDefaultStyle());
+    }
+
+    /** State of parser while preparing highlighted output. */
+    private enum State {
+        QUOTED(
+                1,
+                (dialect) -> "'",
+                (dialect) -> "'",
+                (asb, style) -> asb.style(style.getQuotedStyle())),
+        SQL_QUOTED_IDENTIFIER(
+                2,
+                (dialect) -> dialect == SqlDialect.HIVE ? "\"" : "`",
+                (dialect) -> dialect == SqlDialect.HIVE ? "\"" : "`",
+                (asb, style) -> asb.style(style.getSqlIdentifierStyle())),
+        ONE_LINE_COMMENTED(
+                3,
+                (dialect) -> "--",
+                (dialect) -> "\n",
+                (asb, style) -> asb.style(style.getCommentStyle())),
+        MULTILINE_COMMENTED(
+                5,
+                (dialect) -> "/*",
+                (dialect) -> "*/",
+                (asb, style) -> asb.style(style.getCommentStyle())),
+        HINTED(
+                4,
+                (dialect) -> "/*+",
+                (dialect) -> "*/",
+                (asb, style) -> asb.style(style.getHintStyle()));
+
+        private final Function<SqlDialect, String> start;
+        private final Function<SqlDialect, String> end;
+
+        private final int order;
+
+        private final BiConsumer<AttributedStringBuilder, 
SyntaxHighlightStyle> consumer;

Review Comment:
   the name is a little confusing. How about `styleSetter`?



##########
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java:
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.gateway.Executor;
+
+import org.jline.reader.LineReader;
+import org.jline.reader.impl.DefaultHighlighter;
+import org.jline.utils.AttributedString;
+import org.jline.utils.AttributedStringBuilder;
+
+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;
+
+import static org.apache.flink.table.client.cli.CliClient.COLOR_SCHEMA_VAR;
+
+/** Sql Client syntax highlighter. */
+public class SqlClientSyntaxHighlighter extends DefaultHighlighter {
+    private static final Set<String> FLINK_KEYWORD_SET;
+    private static final Set<String> HIVE_KEYWORD_SET;
+
+    static {
+        try (InputStream is =
+                
SqlClientSyntaxHighlighter.class.getResourceAsStream("/keywords.properties")) {
+            Properties props = new Properties();
+            props.load(is);
+            FLINK_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("default").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+            HIVE_KEYWORD_SET =
+                    Collections.unmodifiableSet(
+                            
Arrays.stream(props.get("hive").toString().split(";"))
+                                    .collect(Collectors.toSet()));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private final Executor executor;
+
+    public SqlClientSyntaxHighlighter(Executor executor) {
+        this.executor = executor;
+    }
+
+    @Override
+    public AttributedString highlight(LineReader reader, String buffer) {
+
+        final Object colorSchemeOrdinal = reader.getVariable(COLOR_SCHEMA_VAR);
+        SyntaxHighlightStyle.BuiltInStyle style =
+                SyntaxHighlightStyle.BuiltInStyle.fromOrdinal(
+                        colorSchemeOrdinal == null ? 0 : (Integer) 
colorSchemeOrdinal);
+        if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) {
+            return super.highlight(reader, buffer);
+        }
+        final SqlDialect dialect =
+                executor.getSessionConfig()
+                                .get(TableConfigOptions.TABLE_SQL_DIALECT)
+                                .equalsIgnoreCase(SqlDialect.HIVE.toString())
+                        ? SqlDialect.HIVE
+                        : SqlDialect.DEFAULT;
+        return getHighlightedOutput(buffer, style.getHighlightStyle(), 
dialect);
+    }
+
+    static AttributedString getHighlightedOutput(

Review Comment:
   Can we do like this?
   ```
   switch (currentChar) {
                   case '\'':
                       if (state == State.SINGLE_QUOTE) {
                           state = State.NORMAL;
                       } else if (state == State.NORMAL) {
                           state = State.SINGLE_QUOTE;
                       }
                       break;
                   case '"':
                       if (state == State.DOUBLE_QUOTE) {
                           state = State.NORMAL;
                       } else if (state == State.NORMAL) {
                           state = State.DOUBLE_QUOTE;
                       }
                       break;
                   case '`':
                       if (state == State.BACK_QUOTE) {
                           state = State.NORMAL;
                       } else if (state == State.NORMAL) {
                           state = State.BACK_QUOTE;
                       }
                       break;
                   case '-':
                       if (lastChar == '-' && state == State.NORMAL) {
                           state = State.SINGLE_COMMENT;
                       }
                       break;
                   case '\n':
                       if (state == State.SINGLE_COMMENT) {
                           state = State.NORMAL;
                       }
                       currentPaddingLineBuilder.setLength(0);
                       currentPaddingSqlBuilder.append("\n");
                       break;
                   case '*':
                       if (lastChar == '/' && state == State.NORMAL) {
                           state = State.MULTI_LINE_COMMENT;
                       }
                       break;
                   case '/':
                       if (lastChar == '*' && state == 
State.MULTI_LINE_COMMENT) {
                           state = State.NORMAL;
                       }
                       break;
   ```
   
   After state is determined, then we apply the style on to the words.



-- 
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