tokenize.go raw

   1  package iskra
   2  
   3  import (
   4  	"bytes"
   5  )
   6  
   7  // Token is one token of code with its class.
   8  type Token struct {
   9  	Text  string
  10  	Class uint8
  11  }
  12  
  13  // Tokenize splits one content string into two-char token chunks by class:
  14  //
  15  //	[0] 0 = punctuation, 1 = identifier/keyword
  16  //	[1] ' ' for anything but a call, '(' for an identifier followed by '('
  17  //
  18  // This is extract.mx TokenizeToken, which the content token pool format is
  19  // defined by: MetaFile.TokenPool records TokenizeToken id runs and the reader
  20  // renders a chunk of two chars back with " ". Joining Decode with " " gives a
  21  // form whose dictionary ids are kept in MetaRecord.Extra[0] for a single-chunk
  22  // token. It is not the language tokenizer (tokenizeEN, tokenizeJA), which is
  23  // part of the extraction port.
  24  func Tokenize(content []byte) []Token {
  25  	var out []Token
  26  	for i := 0; i < len(content); i += 2 {
  27  		end := i + 2
  28  		end = min(end, len(content))
  29  		chunk := content[i:end]
  30  		isIdent := chunk[0] == '_' || chunk[0] >= 'a' && chunk[0] <= 'z' ||
  31  			chunk[0] >= 'A' && chunk[0] <= 'Z'
  32  		class := TokModifier
  33  		if isIdent {
  34  			class = TokNoun
  35  			if len(chunk) > 1 && chunk[1] == '(' {
  36  				class = TokVerb
  37  			}
  38  		}
  39  		out = append(out, Token{Text: string(chunk), Class: class})
  40  	}
  41  	return out
  42  }
  43  
  44  // TokenizeWords splits text into whole-word tokens for a word dictionary:
  45  // identifier runs, decimal and hex numbers, quoted and raw strings, a run of
  46  // same-class punctuation, and each whitespace run as one token, so that joining
  47  // the tokens reproduces the input exactly.
  48  func TokenizeWords(content []byte) []Token {
  49  	var out []Token
  50  	i, n := 0, len(content)
  51  	for i < n {
  52  		c := content[i]
  53  		switch {
  54  		case c == '\n' || c == '\r':
  55  			out = append(out, Token{Text: string(c), Class: TokModifier})
  56  			i++
  57  		case c == ' ' || c == '\t':
  58  			j := i
  59  			for j < n && (content[j] == ' ' || content[j] == '\t') {
  60  				j++
  61  			}
  62  			out = append(out, Token{Text: string(content[i:j]), Class: TokModifier})
  63  			i = j
  64  		case isIdentStart(c) || c >= 0x80:
  65  			j := i
  66  			for j < n && (isIdentStart(content[j]) || (content[j] >= '0' && content[j] <= '9') || content[j] >= 0x80) {
  67  				j++
  68  			}
  69  			class := TokNoun
  70  			if j < n && content[j] == '(' {
  71  				class = TokVerb
  72  			}
  73  			out = append(out, Token{Text: string(content[i:j]), Class: class})
  74  			i = j
  75  		case c >= '0' && c <= '9':
  76  			j := i
  77  			for j < n && (isIdentStart(content[j]) || (content[j] >= '0' && content[j] <= '9') || content[j] == '.') {
  78  				j++
  79  			}
  80  			out = append(out, Token{Text: string(content[i:j]), Class: TokLiteral})
  81  			i = j
  82  		case c == '"' || c == '`' || c == '\'':
  83  			j := i + 1
  84  			for j < n {
  85  				if content[j] == '\\' && j+1 < n {
  86  					j += 2
  87  					continue
  88  				}
  89  				if content[j] == c {
  90  					j++
  91  					break
  92  				}
  93  				j++
  94  			}
  95  			if j > n {
  96  				j = n
  97  			}
  98  			out = append(out, Token{Text: string(content[i:j]), Class: TokLiteral})
  99  			i = j
 100  		default:
 101  			j := i + 1
 102  			for j < n && punctClass(content[j]) == punctClass(c) && content[j] != '"' && content[j] != '`' && content[j] != '\'' {
 103  				j++
 104  			}
 105  			out = append(out, Token{Text: string(content[i:j]), Class: TokModifier})
 106  			i = j
 107  		}
 108  	}
 109  	return out
 110  }
 111  
 112  func isIdentStart(c byte) bool {
 113  	return c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
 114  }
 115  
 116  // punctClass groups operator bytes so runs of them tokenise as one token.
 117  func punctClass(c byte) int {
 118  	switch c {
 119  	case '=', '+', '-', '*', '/', '<', '>', '!', '&', '|', '^', '%':
 120  		return 1
 121  	case ':':
 122  		return 2
 123  	case '.', ',':
 124  		return 3
 125  	default:
 126  		return 4
 127  	}
 128  }
 129  
 130  // SplitLines splits on '\n', dropping a trailing '\r'.
 131  func SplitLines(data []byte) [][]byte {
 132  	var lines [][]byte
 133  	for len(data) > 0 {
 134  		idx := bytes.IndexByte(data, '\n')
 135  		if idx < 0 {
 136  			lines = append(lines, data)
 137  			break
 138  		}
 139  		line := data[:idx]
 140  		if len(line) > 0 && line[len(line)-1] == '\r' {
 141  			line = line[:len(line)-1]
 142  		}
 143  		lines = append(lines, line)
 144  		data = data[idx+1:]
 145  	}
 146  	return lines
 147  }
 148  
 149  // SplitTabs splits a line on '\t'.
 150  func SplitTabs(line []byte) [][]byte {
 151  	return bytes.Split(line, []byte{'\t'})
 152  }
 153  
 154  // SplitTabString splits a string on '\t'.
 155  func SplitTabString(s string) []string {
 156  	return bytesToStrings(bytes.Split([]byte(s), []byte{'\t'}))
 157  }
 158  
 159  func bytesToStrings(bs [][]byte) []string {
 160  	out := make([]string, len(bs))
 161  	for i, b := range bs {
 162  		out[i] = string(b)
 163  	}
 164  	return out
 165  }
 166