This repository has been archived by the owner on Jan 13, 2024. It is now read-only.
/
lexer.go
106 lines (98 loc) · 2.22 KB
/
lexer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Copyright (c) Gabriel de Quadros Ligneul
// SPDX-License-Identifier: MIT (see LICENSE)
package compiler
import (
"fmt"
"regexp"
"strings"
)
func checkEmpty(name string) error {
if len(name) < 1 {
return fmt.Errorf("empty name")
}
return nil
}
func checkFirstChar(name string) error {
pattern := "^[a-zA-Z].*"
regexpPattern := regexp.MustCompile(pattern)
if !regexpPattern.MatchString(name) {
return fmt.Errorf("invalid first rune '%c'", name[0])
}
return nil
}
func checkChars(name string) error {
pattern := "[^a-zA-Z0-9]"
regexpPattern := regexp.MustCompile(pattern)
match := regexpPattern.FindString(name)
if match != "" {
return fmt.Errorf("invalid rune '%v'", match)
}
return nil
}
func checkKeyword(name string) error {
var keyword = map[string]bool{
"break": true,
"case": true,
"chan": true,
"const": true,
"continue": true,
"default": true,
"defer": true,
"else": true,
"fallthrough": true,
"for": true,
"func": true,
"go": true,
"goto": true,
"if": true,
"import": true,
"interface": true,
"iota": true,
"map": true,
"make": true,
"new": true,
"package": true,
"range": true,
"return": true,
"select": true,
"struct": true,
"switch": true,
"type": true,
"var": true,
}
_, ok := keyword[name]
if ok {
return fmt.Errorf("%s is a Go keyword", name)
}
return nil
}
func checkName(name string) error {
checks := []func(string) error{
checkEmpty,
checkFirstChar,
checkChars,
checkKeyword,
}
for _, check := range checks {
if err := check(name); err != nil {
return err
}
}
return nil
}
func tokenizeType(rawType string) (name string, isArray bool, err error) {
openBracketIndex := strings.IndexRune(rawType, '[')
if openBracketIndex != -1 {
isArray = true
if len(rawType) != (openBracketIndex+2) || rawType[openBracketIndex+1] != ']' {
return "", false, fmt.Errorf("invalid array; only [] is supported")
}
name = rawType[:openBracketIndex]
} else {
name = rawType
}
if err := checkName(name); err != nil {
return "", false, err
}
return name, isArray, nil
}