Mercurial Hosting > luan
annotate src/luan/modules/parsers/Csv.java @ 1802:ca98dee04e08 default tip
add Parsers.json_null
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Sun, 21 Apr 2024 21:25:15 -0600 |
parents | b89212fd04b5 |
children |
rev | line source |
---|---|
585 | 1 package luan.modules.parsers; |
2 | |
1333
25746915a241
merge Luan and LuanState
Franklin Schmidt <fschmidt@gmail.com>
parents:
1330
diff
changeset
|
3 import luan.Luan; |
585 | 4 import luan.LuanTable; |
1330 | 5 import luan.LuanException; |
1402
27efb1fcbcb5
move luan.lib to goodjava
Franklin Schmidt <fschmidt@gmail.com>
parents:
1333
diff
changeset
|
6 import goodjava.parser.Parser; |
27efb1fcbcb5
move luan.lib to goodjava
Franklin Schmidt <fschmidt@gmail.com>
parents:
1333
diff
changeset
|
7 import goodjava.parser.ParseException; |
585 | 8 |
9 | |
10 public final class Csv { | |
11 | |
1562 | 12 public static LuanTable toList(String line) throws ParseException { |
1330 | 13 try { |
1562 | 14 return new Csv(line).parse(); |
1330 | 15 } catch(LuanException e) { |
16 throw new RuntimeException(e); | |
17 } | |
585 | 18 } |
19 | |
20 private final Parser parser; | |
21 | |
22 private Csv(String line) { | |
23 this.parser = new Parser(line); | |
24 } | |
25 | |
26 private ParseException exception(String msg) { | |
27 return new ParseException(parser,msg); | |
28 } | |
29 | |
1562 | 30 private LuanTable parse() throws ParseException, LuanException { |
31 LuanTable list = new LuanTable(); | |
585 | 32 while(true) { |
33 Spaces(); | |
34 String field = parseField(); | |
1562 | 35 list.rawPut(list.rawLength()+1,field); |
585 | 36 Spaces(); |
37 if( parser.endOfInput() ) | |
38 return list; | |
39 if( !parser.match(',') ) | |
40 throw exception("unexpected char"); | |
41 } | |
42 } | |
43 | |
44 private String parseField() throws ParseException { | |
45 parser.begin(); | |
46 String rtn; | |
47 if( parser.match('"') ) { | |
48 int start = parser.currentIndex(); | |
49 do { | |
50 if( parser.endOfInput() ) { | |
51 parser.failure(); | |
52 throw exception("unclosed quote"); | |
53 } | |
54 } while( parser.noneOf("\"") ); | |
55 rtn = parser.textFrom(start); | |
56 parser.match('"'); | |
57 } else { | |
58 int start = parser.currentIndex(); | |
59 while( !parser.endOfInput() && parser.noneOf(",") ); | |
60 rtn = parser.textFrom(start).trim(); | |
61 } | |
62 return parser.success(rtn); | |
63 } | |
64 | |
65 private void Spaces() { | |
66 while( parser.anyOf(" \t") ); | |
67 } | |
68 | |
69 } |