1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "utils/grammar/parsing/lexer.h"
18
19 namespace libtextclassifier3::grammar {
20
GetSymbolType(const UnicodeText::const_iterator & it) const21 Symbol::Type Lexer::GetSymbolType(const UnicodeText::const_iterator& it) const {
22 if (unilib_.IsPunctuation(*it)) {
23 return Symbol::Type::TYPE_PUNCTUATION;
24 } else if (unilib_.IsDigit(*it)) {
25 return Symbol::Type::TYPE_DIGITS;
26 } else {
27 return Symbol::Type::TYPE_TERM;
28 }
29 }
30
AppendTokenSymbols(const StringPiece value,int match_offset,const CodepointSpan codepoint_span,std::vector<Symbol> * symbols) const31 void Lexer::AppendTokenSymbols(const StringPiece value, int match_offset,
32 const CodepointSpan codepoint_span,
33 std::vector<Symbol>* symbols) const {
34 // Possibly split token.
35 UnicodeText token_unicode = UTF8ToUnicodeText(value.data(), value.size(),
36 /*do_copy=*/false);
37 int next_match_offset = match_offset;
38 auto token_end = token_unicode.end();
39 auto it = token_unicode.begin();
40 Symbol::Type type = GetSymbolType(it);
41 CodepointIndex sub_token_start = codepoint_span.first;
42 while (it != token_end) {
43 auto next = std::next(it);
44 int num_codepoints = 1;
45 Symbol::Type next_type;
46 while (next != token_end) {
47 next_type = GetSymbolType(next);
48 if (type == Symbol::Type::TYPE_PUNCTUATION || next_type != type) {
49 break;
50 }
51 ++next;
52 ++num_codepoints;
53 }
54 symbols->emplace_back(
55 type, CodepointSpan{sub_token_start, sub_token_start + num_codepoints},
56 /*match_offset=*/next_match_offset,
57 /*lexeme=*/
58 StringPiece(it.utf8_data(), next.utf8_data() - it.utf8_data()));
59 next_match_offset = sub_token_start + num_codepoints;
60 it = next;
61 type = next_type;
62 sub_token_start = next_match_offset;
63 }
64 }
65
66 } // namespace libtextclassifier3::grammar
67