shiguredo_toml 2026.2.0

TOML Library
Documentation
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use alloc::borrow::ToOwned;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::str::FromStr;

use crate::TomlVersion;
use crate::error::Error;
use crate::parser;
use crate::serializer::format_key;
use crate::span::{CommentIndex, PathSegment, SectionIndex, SpanIndex, TextSpan, parse_value_path};
use crate::value::{Table, Value};

/// 元テキストを保持しながら値を更新できる TOML ドキュメント。
#[derive(Debug, Clone)]
pub struct Document {
    source: String,
    table: Table,
    spans: SpanIndex,
    comments: CommentIndex,
    sections: SectionIndex,
}

impl Document {
    /// TOML 文字列から編集可能ドキュメントを作成する。
    pub fn parse(input: &str) -> Result<Self, Error> {
        let (table, spans, comments, sections) =
            parser::parse_with_spans(input, TomlVersion::V1_0)?;
        Ok(Self {
            source: input.to_owned(),
            table,
            spans,
            comments,
            sections,
        })
    }

    /// 現在の TOML テキストを返す。
    pub fn as_str(&self) -> &str {
        &self.source
    }

    /// 現在のルートテーブルを返す。
    pub fn as_table(&self) -> &Table {
        &self.table
    }

    /// 値位置インデックスを返す。
    pub fn spans(&self) -> &SpanIndex {
        &self.spans
    }

    /// コメント位置インデックスを返す。
    pub fn comments(&self) -> &CommentIndex {
        &self.comments
    }

    /// 指定パスの範囲を返す。
    pub fn span(&self, path: &[PathSegment]) -> Option<TextSpan> {
        self.spans.get(path)
    }

    /// 指定パスに紐づく行末コメント範囲を返す。
    pub fn trailing_comment_span(&self, path: &[PathSegment]) -> Option<TextSpan> {
        self.comments.trailing_for(path)
    }

    /// 文字列パスで指定した行末コメント範囲を返す。
    pub fn trailing_comment_span_path(&self, path: &str) -> Option<TextSpan> {
        let parsed = parse_value_path(path).ok()?;
        self.trailing_comment_span(&parsed)
    }

    /// 指定パスの値を返す。
    pub fn get(&self, path: &[PathSegment]) -> Option<&Value> {
        value_at_path(&self.table, path)
    }

    /// 文字列パスで指定した値を返す。
    pub fn get_path(&self, path: &str) -> Option<&Value> {
        let parsed = parse_value_path(path).ok()?;
        self.get(&parsed)
    }

    /// セクション位置インデックスを返す。
    pub fn sections(&self) -> &SectionIndex {
        &self.sections
    }

    /// 指定パスの値を置換、またはパスが存在しなければ新規挿入する。
    ///
    /// 中間テーブルが存在しない場合はセクションヘッダを自動生成する。
    /// 更新後に全体を再解析し、位置情報も更新する。
    pub fn set(&mut self, path: &[PathSegment], new_value: Value) -> Result<(), Error> {
        if let Some(span) = self.spans.get(path) {
            // 既存値の置換
            let replacement = crate::to_inline_string(&new_value)?;

            if span.start > span.end || span.end > self.source.len() {
                return Err(Error::serialize("invalid value span"));
            }

            let mut next_source = self.source.clone();
            next_source.replace_range(span.start..span.end, &replacement);

            self.reparse(next_source)
        } else {
            // 新規挿入
            self.insert_at_path(path, new_value)
        }
    }

    /// 文字列パスで指定した値を置換、またはパスが存在しなければ新規挿入する。
    pub fn set_path(&mut self, path: &str, new_value: Value) -> Result<(), Error> {
        let parsed = parse_value_path(path)?;
        self.set(&parsed, new_value)
    }

    /// ソーステキストを再パースして内部状態を更新する。
    fn reparse(&mut self, next_source: String) -> Result<(), Error> {
        let (next_table, next_spans, next_comments, next_sections) =
            parser::parse_with_spans(&next_source, TomlVersion::V1_0)?;
        self.source = next_source;
        self.table = next_table;
        self.spans = next_spans;
        self.comments = next_comments;
        self.sections = next_sections;
        Ok(())
    }

    /// パスが存在しない場合に新規キー値ペアを挿入する。
    fn insert_at_path(&mut self, path: &[PathSegment], new_value: Value) -> Result<(), Error> {
        // 末尾セグメントが Key であることを要求する
        let last = path.last().ok_or_else(|| Error::serialize("empty path"))?;
        let PathSegment::Key(key) = last else {
            return Err(Error::serialize("cannot insert an array element via set"));
        };

        let parent_path = &path[..path.len() - 1];

        // 親がインラインテーブルかどうかを判定する
        if !parent_path.is_empty()
            && let Some(parent_span) = self.spans.get(parent_path)
        {
            let parent_text = &self.source[parent_span.start..parent_span.end];
            if parent_text.starts_with('{') {
                return self.insert_into_inline_table(path, new_value);
            }
        }

        // 親テーブルが存在しない場合はセクションヘッダを自動生成して挿入する
        if !parent_path.is_empty() && value_at_path(&self.table, parent_path).is_none() {
            return self.insert_with_new_section(path, new_value);
        }

        // セクションテーブルまたはルートへの挿入
        let inline_value = crate::to_inline_string(&new_value)?;
        let key_text = format_key(key);
        let insert_text = format!("{key_text} = {inline_value}\n");

        let insert_pos = self.find_insert_position(parent_path)?;

        // 挿入位置の直前が改行でない場合は改行を補う
        let needs_newline = insert_pos > 0 && self.source.as_bytes()[insert_pos - 1] != b'\n';

        let mut next_source = self.source.clone();
        if needs_newline {
            next_source.insert_str(insert_pos, &format!("\n{insert_text}"));
        } else {
            next_source.insert_str(insert_pos, &insert_text);
        }

        self.reparse(next_source)
    }

    /// 親パスに基づいてセクションテーブルまたはルートへの挿入位置を決定する。
    fn find_insert_position(&self, parent_path: &[PathSegment]) -> Result<usize, Error> {
        if parent_path.is_empty() {
            // ルートレベルへの挿入
            let pos = strip_trailing_blank_lines(&self.source, self.sections.root_end);
            return Ok(pos);
        }

        // 親が存在するか確認する
        let parent_value = value_at_path(&self.table, parent_path)
            .ok_or_else(|| Error::serialize("parent table does not exist"))?;

        match parent_value {
            Value::Table(_) => {}
            _ => {
                return Err(Error::serialize("parent path does not point to a table"));
            }
        }

        // セクションテーブル: SectionIndex からセクションの body_end に挿入する
        // body_end は次のセクションヘッダ直前を指すため、末尾の空行を除いた位置に挿入する
        if let Some(section_span) = self.sections.get(parent_path) {
            let pos = strip_trailing_blank_lines(&self.source, section_span.body_end);
            return Ok(pos);
        }

        Err(Error::serialize(
            "cannot determine insert position for the parent table",
        ))
    }

    /// 親テーブルが存在しない場合にセクションヘッダを自動生成して挿入する。
    fn insert_with_new_section(
        &mut self,
        path: &[PathSegment],
        new_value: Value,
    ) -> Result<(), Error> {
        let last = match path.last() {
            Some(PathSegment::Key(key)) => key,
            _ => return Err(Error::serialize("leaf must be a key")),
        };

        let parent_path = &path[..path.len() - 1];

        // 中間パスを検証する
        self.validate_intermediate_path(parent_path)?;

        // セクションヘッダを組み立てる
        let header = format_section_header(parent_path);

        // キー値行を組み立てる
        let inline_value = crate::to_inline_string(&new_value)?;
        let key_text = format_key(last);
        let insert_text = format!("{header}\n{key_text} = {inline_value}\n");

        // 最も近い既存セクションの末尾に挿入する
        let insert_pos = self.find_ancestor_section_end(parent_path)?;

        // 挿入位置の直前が改行でない場合は改行を補う
        let needs_newline = insert_pos > 0 && self.source.as_bytes()[insert_pos - 1] != b'\n';

        let mut next_source = self.source.clone();
        if needs_newline {
            next_source.insert_str(insert_pos, &format!("\n{insert_text}"));
        } else {
            next_source.insert_str(insert_pos, &insert_text);
        }

        self.reparse(next_source)
    }

    /// 自動作成パスの中間セグメントを検証する。
    ///
    /// - 既存値がテーブル以外(スカラー、配列)であればエラー
    /// - 欠損部分に Index セグメントがあればエラー
    fn validate_intermediate_path(&self, parent_path: &[PathSegment]) -> Result<(), Error> {
        let mut found_missing = false;
        for i in 0..parent_path.len() {
            if found_missing {
                // 欠損部分では Index セグメントを許可しない
                if matches!(parent_path[i], PathSegment::Index(_)) {
                    return Err(Error::serialize("cannot auto-create array elements"));
                }
                continue;
            }
            let partial = &parent_path[..=i];
            match value_at_path(&self.table, partial) {
                Some(v) if v.is_table() => {}
                Some(_) => {
                    return Err(Error::serialize("intermediate path is not a table"));
                }
                None => {
                    if matches!(parent_path[i], PathSegment::Index(_)) {
                        return Err(Error::serialize("cannot auto-create array elements"));
                    }
                    found_missing = true;
                }
            }
        }
        Ok(())
    }

    /// 親パスから逆順に辿り、最も近い既存セクションの body_end を返す。
    /// セクションが見つからなければルート末尾を返す。
    fn find_ancestor_section_end(&self, parent_path: &[PathSegment]) -> Result<usize, Error> {
        for depth in (1..=parent_path.len()).rev() {
            let candidate = &parent_path[..depth];
            if let Some(section_span) = self.sections.get(candidate) {
                return Ok(strip_trailing_blank_lines(
                    &self.source,
                    section_span.body_end,
                ));
            }
        }
        Ok(strip_trailing_blank_lines(
            &self.source,
            self.sections.root_end,
        ))
    }

    /// インラインテーブル内への新規キー挿入テキストを生成する。
    fn insert_into_inline_table(
        &mut self,
        path: &[PathSegment],
        new_value: Value,
    ) -> Result<(), Error> {
        let last = path.last().ok_or_else(|| Error::serialize("empty path"))?;
        let PathSegment::Key(key) = last else {
            return Err(Error::serialize("cannot insert an array element via set"));
        };

        let parent_path = &path[..path.len() - 1];
        let parent_span = self
            .spans
            .get(parent_path)
            .ok_or_else(|| Error::serialize("parent span not found"))?;

        let parent_value = value_at_path(&self.table, parent_path)
            .ok_or_else(|| Error::serialize("parent table does not exist"))?;
        let parent_table = parent_value
            .as_table()
            .ok_or_else(|| Error::serialize("parent is not a table"))?;

        let inline_value = crate::to_inline_string(&new_value)?;
        let key_text = format_key(key);

        // 閉じ } の位置
        let close_brace_pos = self.source[..parent_span.end]
            .rfind('}')
            .ok_or_else(|| Error::serialize("inline table closing brace not found"))?;

        // 閉じ } の直前にスペースがあるかチェックして、整形を保つ
        let has_space_before_brace =
            close_brace_pos > 0 && self.source.as_bytes()[close_brace_pos - 1] == b' ';

        let insert_text = if parent_table.is_empty() {
            format!("{key_text} = {inline_value}")
        } else {
            // "{ a = 1 }" -> "{ a = 1, b = 2 }"
            // has_space_before_brace の場合はスペースの前に挿入するため、スペースは維持される
            format!(", {key_text} = {inline_value}")
        };

        // スペースがある場合はスペースの前に挿入する
        let insert_pos = if has_space_before_brace {
            close_brace_pos - 1
        } else {
            close_brace_pos
        };

        let mut next_source = self.source.clone();
        next_source.insert_str(insert_pos, &insert_text);

        self.reparse(next_source)
    }
}

impl FromStr for Document {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// ValuePath からセクションヘッダ文字列を組み立てる。
/// Index セグメントはスキップする(TOML の配列テーブル文脈で暗黙的に解決される)。
fn format_section_header(path: &[PathSegment]) -> String {
    let keys: Vec<String> = path
        .iter()
        .filter_map(|seg| match seg {
            PathSegment::Key(k) => Some(format_key(k)),
            PathSegment::Index(_) => None,
        })
        .collect();
    format!("[{}]", keys.join("."))
}

/// セクション body_end から末尾の空行(空白のみの行を含む)を逆方向にスキップし、
/// 最後の有効な行の直後の位置を返す。
fn strip_trailing_blank_lines(source: &str, body_end: usize) -> usize {
    let bytes = source.as_bytes();
    let mut pos = body_end;

    // 末尾の空行を逆方向にスキップする
    while pos > 0 && bytes[pos - 1] == b'\n' {
        // 改行の直前をスキャンして、行の内容が空白のみかどうかを判定する
        let line_end = pos - 1;
        let mut line_start = line_end;
        while line_start > 0 && bytes[line_start - 1] != b'\n' {
            line_start -= 1;
        }
        // 行の内容が空白のみであれば空行とみなしてスキップする
        let line_content = &bytes[line_start..line_end];
        if line_content.iter().all(|&b| b == b' ' || b == b'\t') {
            pos = line_start;
        } else {
            break;
        }
    }

    pos
}

fn value_at_path<'a>(table: &'a Table, path: &[PathSegment]) -> Option<&'a Value> {
    let (first, rest) = path.split_first()?;
    let mut current = match first {
        PathSegment::Key(key) => table.get(key)?,
        PathSegment::Index(_) => return None,
    };

    for segment in rest {
        match segment {
            PathSegment::Key(key) => {
                current = current.as_table()?.get(key)?;
            }
            PathSegment::Index(index) => {
                current = current.as_array()?.get(*index)?;
            }
        }
    }

    Some(current)
}