summaryrefslogtreecommitdiff
path: root/lib/inifile/parse.myr
blob: 6276cf801c438ff20525709993f349afec4aa622 (plain)
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use std
use bio

use "types"

pkg inifile =
	/* reading */
	const load	: (path : byte[:]	-> std.result(inifile#, error))
	const loadf	: (file : std.fd	-> std.result(inifile#, error))
	const free	: (ini : inifile#	-> void)
;;


type parser = struct
	line	: int
	sect	: byte[:]
	err	: std.option(error)
;;

const load = {path
	match std.open(path, std.Oread)
	| `std.Ok fd:	-> loadf(fd)
	| `std.Err e:	-> `std.Err `Fileerr
	;;
}

const free = {ini
	for ((sect, key), val) : std.byhtkeyvals(ini.elts)
		std.slfree(val)
		std.slfree(sect)
		std.slfree(key)
	;;
	for s : ini.sects
		std.slfree(s)
	;;
	std.slfree(ini.sects)
	std.htfree(ini.elts)
	std.free(ini)
}

const loadf = {fd
	var p : parser#
	var ini
	var f

	ini = std.mk([
		.elts = std.mkht()
	])
	p = std.mk([
		.line = 1,
		.sect = "",
		.err = `std.None
	])
	f = bio.mkfile(fd, bio.Rd)
	while true
		match bio.readln(f)
		| `std.Err `bio.Eof:
			break
		| `std.Ok ln:
			if !parseline(p, ini, ln)
				break
			;;
		| `std.Err e:
			p.err = `std.Some `Fileerr
			break
		;;
		p.line++
	;;
	match p.err
	| `std.None:
		std.slfree(p.sect)
		-> `std.Ok ini 
	| `std.Some e:
		free(ini)
		-> `std.Err e
	;;
}

const parseline = {p, ini, ln
	ln = std.strstrip(ln)

	/* remove comments */
	match std.strfind(ln, ";")
	| `std.Some idx:	ln = ln[:idx]
	| `std.None:
	;;
	match std.strfind(ln, "#")
	| `std.Some idx:	ln = ln[:idx]
	| `std.None:
	;;

	/* skip empty lines */
	if ln.len == 0
		-> true
	;;

	match (ln[0] : char)
	| '[':	-> parsesection(p, ini, ln)
	| _:	-> parsekvp(p, ini, ln)
	;;
}

const parsesection = {p, ini, ln
	match std.strfind(ln, "]")
	| `std.Some idx:
		if idx != ln.len - 1
			p.err = `std.Some (`Parseerr p.line)
			-> false
		;;
		std.slfree(p.sect)
		p.sect = std.sldup(std.strstrip(ln[1:idx]))
		match std.lsearch(ini.sects, p.sect, std.strcmp)
		| `std.Some s:	/* nothing */
		| `std.None:	std.slpush(&ini.sects, std.sldup(p.sect))
		;;
	| `std.None:
		p.err = `std.Some (`Parseerr p.line)
		-> false
	;;
	-> true
}

const parsekvp = {p, ini, ln
	var key, val

	match std.strfind(ln, "=")
	| `std.None:
		p.err = `std.Some (`Parseerr p.line)
		-> false
	| `std.Some idx:
		key = std.strstrip(ln[:idx])
		val = std.strstrip(ln[idx+1:])
		if std.hthas(ini.elts, (p.sect, key))
			p.err = `std.Some(`Dupkey p.line)
			-> false
		;;
		std.htput(ini.elts, (std.sldup(p.sect), std.sldup(key)), std.sldup(val))
		-> true
	;;
}