github.com/whtcorpsinc/MilevaDB-Prod@v0.0.0-20211104133533-f57f4be3b597/soliton/berolinaSQL/parser.go (about) 1 // Copyright 2020 WHTCORPS INC, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package BerolinaSQL 15 16 import ( 17 "strconv" 18 "unicode" 19 20 "github.com/whtcorpsinc/errors" 21 ) 22 23 var ( 24 // ErrPatternNotMatch represents an error that patterns doesn't match. 25 ErrPatternNotMatch = errors.New("Pattern not match") 26 ) 27 28 // Match matches the `pat` at least `times`, and returns the match, the rest and the error 29 func Match(buf string, pat func(byte) bool, times int) (string, string, error) { 30 var i int 31 for i = 0; i < len(buf) && pat(buf[i]); i++ { 32 } 33 if i < times { 34 return "", buf, ErrPatternNotMatch 35 } 36 return buf[:i], buf[i:], nil 37 } 38 39 // MatchOne matches only one time with pat 40 func MatchOne(buf string, pat func(byte) bool) (string, error) { 41 if len(buf) == 0 || !pat(buf[0]) { 42 return buf, ErrPatternNotMatch 43 } 44 return buf[1:], nil 45 } 46 47 // AnyPunct matches an arbitrary punctuation 48 func AnyPunct(buf string) (string, error) { 49 return MatchOne(buf, func(b byte) bool { 50 return unicode.IsPunct(rune(b)) 51 }) 52 } 53 54 // AnyChar matches an arbitrary character 55 func AnyChar(buf string) (string, error) { 56 return MatchOne(buf, func(byte) bool { 57 return true 58 }) 59 } 60 61 // Char matches a character: c 62 func Char(buf string, c byte) (string, error) { 63 return MatchOne(buf, func(x byte) bool { 64 return x == c 65 }) 66 } 67 68 // Space matches at least `times` spaces 69 func Space(buf string, times int) (string, error) { 70 _, rest, err := Match(buf, func(c byte) bool { 71 return unicode.IsSpace(rune(c)) 72 }, times) 73 return rest, err 74 } 75 76 // Space0 matches at least 0 space. 77 func Space0(buf string) string { 78 rest, err := Space(buf, 0) 79 if err != nil { 80 panic(err) 81 } 82 return rest 83 } 84 85 // Digit matches at least `times` digits 86 func Digit(buf string, times int) (string, string, error) { 87 return Match(buf, func(c byte) bool { 88 return unicode.IsDigit(rune(c)) 89 }, times) 90 } 91 92 // Number matches a series of digits and convert it to an int 93 func Number(str string) (int, string, error) { 94 digits, rest, err := Digit(str, 1) 95 if err != nil { 96 return 0, str, err 97 } 98 num, err := strconv.Atoi(digits) 99 return num, rest, err 100 }