scripts.split

  1from utils import *
  2from pico_process import SubLanguageBase
  3from pico_parse import VarKind
  4from pico_tokenize import parse_char_escape
  5
  6@lru_cache
  7def parse_split_args(args, lang):
  8    """args is e.g. 'member=string' or '(global.members)=string'
  9       return value is (separator, split parts, plural begin idx, plural end idx)"""
 10    idx = 0
 11
 12    def peek_char():
 13        return str_get(args, idx, "\0")
 14
 15    def take_char():
 16        nonlocal idx
 17        ch = peek_char()
 18        idx += 1
 19        return ch
 20
 21    def parse_rec(depth):
 22        nonlocal idx
 23        start = idx
 24        split = []
 25        sep = None
 26        sep_expected = False
 27        plural_begin = plural_end = None
 28        while True:
 29            ch = take_char()
 30            if ch == "\0":
 31                if depth:
 32                    throw("unexpected end of arguments (unbalanced '('?)")
 33                break
 34            elif ch == ")":
 35                if not depth:
 36                    throw("unbalanced ')'")
 37                break
 38            elif ch == "(":
 39                if sep_expected:
 40                    throw(f"missing separator before '('")
 41                split.append(parse_rec(depth + 1))
 42                sep_expected = True
 43            elif ch.isalpha():
 44                word = ch
 45                while peek_char().isalpha():
 46                    word += take_char()
 47
 48                is_plural = False
 49                singular = word
 50                if word.endswith("s"):
 51                    is_plural = True
 52                    singular = word[:-1]
 53
 54                if singular == "member":
 55                    split.append(VarKind.member)
 56                elif singular == "global":
 57                    split.append(VarKind.global_)
 58                elif singular == "string" or singular == "preserve":
 59                    split.append(None)
 60                elif singular == "": # just "s", e.g. after parentheses
 61                    if not split or not isinstance(split[-1], tuple):
 62                        throw(f"missing parentheses before {word}")
 63                else:
 64                    throw(f"invalid variable type: {word} (use member/global/string, optionally plural)")
 65                
 66                if is_plural:
 67                    if plural_begin is None:
 68                        plural_begin = len(split) - 1
 69                        plural_end = plural_begin + 1
 70                    elif plural_end == len(split) - 1:
 71                        plural_end += 1
 72                    else:
 73                        throw(f"multiple plural variable types must be consecutive")
 74
 75                if sep_expected and singular != "":
 76                    throw(f"missing separator before {word}")
 77                sep_expected = True
 78            else:
 79                if ch == "\\":
 80                    if (ch := str_get(args, idx, "")) in "()":
 81                        idx += 1
 82                    elif ch == "w":
 83                        ch = str_get(args, idx + 1, "")
 84                        idx += 2
 85                    else:
 86                        ch, idx = parse_char_escape(args, idx - 1, lang)
 87                
 88                if sep is None:
 89                    sep = ch
 90                elif sep != ch:
 91                    throw(f"parentheses must be used to clarify order of splitting by {sep} and {ch}")
 92                    
 93                if not sep_expected:
 94                    throw(f"expected variable type before separator {ch}")
 95                sep_expected = False
 96        
 97        if sep is None:
 98            throw(f"no separator specified for: {args[start:idx]} - you can add a separator at the end")
 99
100        return (sep, split, plural_begin, plural_end)
101    
102    return parse_rec(0)
103
104class SplitSubLang(SubLanguageBase):
105    """Implements a simple split()-based language, where the interpretation of each split part
106    is customizable via the language args"""
107
108    def __init__(m, text, args, ctxt, on_error, **_):
109        try:
110            template = parse_split_args(args, ctxt.lang)
111        except CheckError as e:
112            on_error(str(e))
113            return
114
115        m.data = m.parse(text, template)
116    
117    def repeat_partial(m, slice, count):
118        slice_i = 0
119        result = []
120        for i in range(count):
121            result.append(slice[slice_i])
122            slice_i += 1
123            if slice_i == len(slice):
124                slice_i = 0
125        return result
126
127    def get_types_of_len(m, parts, types, plural_begin, plural_end):
128        """get 'types' with the size of 'parts', expanding/shrinking per plural_begin/end as needed"""
129
130        if len(parts) != len(types):
131            if plural_begin is None:
132                if len(types) < len(parts):
133                    types += [None] * (len(parts) - len(types))
134            else:
135                repeat_len = len(parts) - len(types) + plural_end - plural_begin
136                repeat = m.repeat_partial(types[plural_begin:plural_end], repeat_len)
137                types = types[:plural_begin] + repeat + types[plural_end:]
138            
139            if len(types) > len(parts):
140                types = types[:len(parts)]
141        
142        return types
143        
144    def parse(m, str, template):
145        """parses 'str', according to 'template'"""
146
147        sep, types, plural_begin, plural_end = template
148        parts = str.split(sep)
149        types = m.get_types_of_len(parts, types, plural_begin, plural_end)
150
151        for i, type in enumerate(types):
152            if isinstance(type, tuple):
153                parts[i] = m.parse(parts[i], type)
154        
155        return (sep, parts, types)
156
157    def collect_usages_of(m, data, kind, usages):
158        _, parts, types = data
159        for part, type in zip(parts, types):
160            if isinstance(type, tuple):
161                m.collect_usages_of(part, kind, usages)
162            elif type == kind:
163                usages[part] += 1
164
165    def get_usages_of(m, kind):
166        usages = CounterDictionary()
167        m.collect_usages_of(m.data, kind, usages)
168        return usages
169
170    def get_global_usages(m, **_):
171        return m.get_usages_of(VarKind.global_)
172    def get_member_usages(m, **_):
173        return m.get_usages_of(VarKind.member)
174
175    def rename_of(m, data, globals, members):
176        _, parts, types = data
177        for i, (part, type) in enumerate(zip(parts, types)):
178            if isinstance(type, tuple):
179                m.rename_of(part, globals, members)
180            elif type == VarKind.global_:
181                parts[i] = globals.get(parts[i], parts[i])
182            elif type == VarKind.member:
183                parts[i] = members.get(parts[i], parts[i])
184
185    def rename(m, globals, members, **_):
186        m.rename_of(m.data, globals, members)
187
188    def format(m, data):
189        sep, parts, _ = data
190        return sep.join((m.format(part) if isinstance(part, tuple) else part) for part in parts)
191    
192    def minify(m, **_):
193        return m.format(m.data)
194
195def sublanguage_main(lang, **_):
196    if lang == "split":
197        return SplitSubLang
@lru_cache
def parse_split_args(args, lang):
  7@lru_cache
  8def parse_split_args(args, lang):
  9    """args is e.g. 'member=string' or '(global.members)=string'
 10       return value is (separator, split parts, plural begin idx, plural end idx)"""
 11    idx = 0
 12
 13    def peek_char():
 14        return str_get(args, idx, "\0")
 15
 16    def take_char():
 17        nonlocal idx
 18        ch = peek_char()
 19        idx += 1
 20        return ch
 21
 22    def parse_rec(depth):
 23        nonlocal idx
 24        start = idx
 25        split = []
 26        sep = None
 27        sep_expected = False
 28        plural_begin = plural_end = None
 29        while True:
 30            ch = take_char()
 31            if ch == "\0":
 32                if depth:
 33                    throw("unexpected end of arguments (unbalanced '('?)")
 34                break
 35            elif ch == ")":
 36                if not depth:
 37                    throw("unbalanced ')'")
 38                break
 39            elif ch == "(":
 40                if sep_expected:
 41                    throw(f"missing separator before '('")
 42                split.append(parse_rec(depth + 1))
 43                sep_expected = True
 44            elif ch.isalpha():
 45                word = ch
 46                while peek_char().isalpha():
 47                    word += take_char()
 48
 49                is_plural = False
 50                singular = word
 51                if word.endswith("s"):
 52                    is_plural = True
 53                    singular = word[:-1]
 54
 55                if singular == "member":
 56                    split.append(VarKind.member)
 57                elif singular == "global":
 58                    split.append(VarKind.global_)
 59                elif singular == "string" or singular == "preserve":
 60                    split.append(None)
 61                elif singular == "": # just "s", e.g. after parentheses
 62                    if not split or not isinstance(split[-1], tuple):
 63                        throw(f"missing parentheses before {word}")
 64                else:
 65                    throw(f"invalid variable type: {word} (use member/global/string, optionally plural)")
 66                
 67                if is_plural:
 68                    if plural_begin is None:
 69                        plural_begin = len(split) - 1
 70                        plural_end = plural_begin + 1
 71                    elif plural_end == len(split) - 1:
 72                        plural_end += 1
 73                    else:
 74                        throw(f"multiple plural variable types must be consecutive")
 75
 76                if sep_expected and singular != "":
 77                    throw(f"missing separator before {word}")
 78                sep_expected = True
 79            else:
 80                if ch == "\\":
 81                    if (ch := str_get(args, idx, "")) in "()":
 82                        idx += 1
 83                    elif ch == "w":
 84                        ch = str_get(args, idx + 1, "")
 85                        idx += 2
 86                    else:
 87                        ch, idx = parse_char_escape(args, idx - 1, lang)
 88                
 89                if sep is None:
 90                    sep = ch
 91                elif sep != ch:
 92                    throw(f"parentheses must be used to clarify order of splitting by {sep} and {ch}")
 93                    
 94                if not sep_expected:
 95                    throw(f"expected variable type before separator {ch}")
 96                sep_expected = False
 97        
 98        if sep is None:
 99            throw(f"no separator specified for: {args[start:idx]} - you can add a separator at the end")
100
101        return (sep, split, plural_begin, plural_end)
102    
103    return parse_rec(0)

args is e.g. 'member=string' or '(global.members)=string' return value is (separator, split parts, plural begin idx, plural end idx)

class SplitSubLang(pico_srcdefs.SubLanguageBase):
105class SplitSubLang(SubLanguageBase):
106    """Implements a simple split()-based language, where the interpretation of each split part
107    is customizable via the language args"""
108
109    def __init__(m, text, args, ctxt, on_error, **_):
110        try:
111            template = parse_split_args(args, ctxt.lang)
112        except CheckError as e:
113            on_error(str(e))
114            return
115
116        m.data = m.parse(text, template)
117    
118    def repeat_partial(m, slice, count):
119        slice_i = 0
120        result = []
121        for i in range(count):
122            result.append(slice[slice_i])
123            slice_i += 1
124            if slice_i == len(slice):
125                slice_i = 0
126        return result
127
128    def get_types_of_len(m, parts, types, plural_begin, plural_end):
129        """get 'types' with the size of 'parts', expanding/shrinking per plural_begin/end as needed"""
130
131        if len(parts) != len(types):
132            if plural_begin is None:
133                if len(types) < len(parts):
134                    types += [None] * (len(parts) - len(types))
135            else:
136                repeat_len = len(parts) - len(types) + plural_end - plural_begin
137                repeat = m.repeat_partial(types[plural_begin:plural_end], repeat_len)
138                types = types[:plural_begin] + repeat + types[plural_end:]
139            
140            if len(types) > len(parts):
141                types = types[:len(parts)]
142        
143        return types
144        
145    def parse(m, str, template):
146        """parses 'str', according to 'template'"""
147
148        sep, types, plural_begin, plural_end = template
149        parts = str.split(sep)
150        types = m.get_types_of_len(parts, types, plural_begin, plural_end)
151
152        for i, type in enumerate(types):
153            if isinstance(type, tuple):
154                parts[i] = m.parse(parts[i], type)
155        
156        return (sep, parts, types)
157
158    def collect_usages_of(m, data, kind, usages):
159        _, parts, types = data
160        for part, type in zip(parts, types):
161            if isinstance(type, tuple):
162                m.collect_usages_of(part, kind, usages)
163            elif type == kind:
164                usages[part] += 1
165
166    def get_usages_of(m, kind):
167        usages = CounterDictionary()
168        m.collect_usages_of(m.data, kind, usages)
169        return usages
170
171    def get_global_usages(m, **_):
172        return m.get_usages_of(VarKind.global_)
173    def get_member_usages(m, **_):
174        return m.get_usages_of(VarKind.member)
175
176    def rename_of(m, data, globals, members):
177        _, parts, types = data
178        for i, (part, type) in enumerate(zip(parts, types)):
179            if isinstance(type, tuple):
180                m.rename_of(part, globals, members)
181            elif type == VarKind.global_:
182                parts[i] = globals.get(parts[i], parts[i])
183            elif type == VarKind.member:
184                parts[i] = members.get(parts[i], parts[i])
185
186    def rename(m, globals, members, **_):
187        m.rename_of(m.data, globals, members)
188
189    def format(m, data):
190        sep, parts, _ = data
191        return sep.join((m.format(part) if isinstance(part, tuple) else part) for part in parts)
192    
193    def minify(m, **_):
194        return m.format(m.data)

Implements a simple split()-based language, where the interpretation of each split part is customizable via the language args

SplitSubLang(text, args, ctxt, on_error, **_)
109    def __init__(m, text, args, ctxt, on_error, **_):
110        try:
111            template = parse_split_args(args, ctxt.lang)
112        except CheckError as e:
113            on_error(str(e))
114            return
115
116        m.data = m.parse(text, template)
def repeat_partial(m, slice, count):
118    def repeat_partial(m, slice, count):
119        slice_i = 0
120        result = []
121        for i in range(count):
122            result.append(slice[slice_i])
123            slice_i += 1
124            if slice_i == len(slice):
125                slice_i = 0
126        return result
def get_types_of_len(m, parts, types, plural_begin, plural_end):
128    def get_types_of_len(m, parts, types, plural_begin, plural_end):
129        """get 'types' with the size of 'parts', expanding/shrinking per plural_begin/end as needed"""
130
131        if len(parts) != len(types):
132            if plural_begin is None:
133                if len(types) < len(parts):
134                    types += [None] * (len(parts) - len(types))
135            else:
136                repeat_len = len(parts) - len(types) + plural_end - plural_begin
137                repeat = m.repeat_partial(types[plural_begin:plural_end], repeat_len)
138                types = types[:plural_begin] + repeat + types[plural_end:]
139            
140            if len(types) > len(parts):
141                types = types[:len(parts)]
142        
143        return types

get 'types' with the size of 'parts', expanding/shrinking per plural_begin/end as needed

def parse(m, str, template):
145    def parse(m, str, template):
146        """parses 'str', according to 'template'"""
147
148        sep, types, plural_begin, plural_end = template
149        parts = str.split(sep)
150        types = m.get_types_of_len(parts, types, plural_begin, plural_end)
151
152        for i, type in enumerate(types):
153            if isinstance(type, tuple):
154                parts[i] = m.parse(parts[i], type)
155        
156        return (sep, parts, types)

parses 'str', according to 'template'

def collect_usages_of(m, data, kind, usages):
158    def collect_usages_of(m, data, kind, usages):
159        _, parts, types = data
160        for part, type in zip(parts, types):
161            if isinstance(type, tuple):
162                m.collect_usages_of(part, kind, usages)
163            elif type == kind:
164                usages[part] += 1
def get_usages_of(m, kind):
166    def get_usages_of(m, kind):
167        usages = CounterDictionary()
168        m.collect_usages_of(m.data, kind, usages)
169        return usages
def get_global_usages(m, **_):
171    def get_global_usages(m, **_):
172        return m.get_usages_of(VarKind.global_)
def get_member_usages(m, **_):
173    def get_member_usages(m, **_):
174        return m.get_usages_of(VarKind.member)
def rename_of(m, data, globals, members):
176    def rename_of(m, data, globals, members):
177        _, parts, types = data
178        for i, (part, type) in enumerate(zip(parts, types)):
179            if isinstance(type, tuple):
180                m.rename_of(part, globals, members)
181            elif type == VarKind.global_:
182                parts[i] = globals.get(parts[i], parts[i])
183            elif type == VarKind.member:
184                parts[i] = members.get(parts[i], parts[i])
def rename(m, globals, members, **_):
186    def rename(m, globals, members, **_):
187        m.rename_of(m.data, globals, members)
def format(m, data):
189    def format(m, data):
190        sep, parts, _ = data
191        return sep.join((m.format(part) if isinstance(part, tuple) else part) for part in parts)
def minify(m, **_):
193    def minify(m, **_):
194        return m.format(m.data)

The type of the None singleton.

def sublanguage_main(lang, **_):
196def sublanguage_main(lang, **_):
197    if lang == "split":
198        return SplitSubLang