-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathbuilder.rs
More file actions
3427 lines (2903 loc) · 109 KB
/
builder.rs
File metadata and controls
3427 lines (2903 loc) · 109 KB
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Plot builder - converts tree-sitter CST to typed Plot
//!
//! Takes a tree-sitter parse tree and builds a typed Plot,
//! handling all the node types defined in the grammar.
use crate::plot::layer::geom::Geom;
use crate::plot::projection::resolve_coord;
use crate::plot::scale::{color_to_hex, is_color_aesthetic, is_user_facet_aesthetic, Transform};
use crate::plot::*;
use crate::{GgsqlError, Result};
use std::collections::HashMap;
use tree_sitter::Node;
use super::SourceTree;
// ============================================================================
// Basic Type Parsers
// ============================================================================
/// Extract 'name' and 'value' field nodes from an assignment-like node
///
/// Returns (name_node, value_node) without any interpretation.
/// Works for both patterns:
/// - `name => value` (SETTING, PROJECT, THEME, LABEL, RENAMING)
/// - `value AS name` (MAPPING explicit_mapping)
///
/// Caller is responsible for interpreting the nodes based on their context.
fn extract_name_value_nodes<'a>(node: &'a Node<'a>, context: &str) -> Result<(Node<'a>, Node<'a>)> {
let name_node = node
.child_by_field_name("name")
.ok_or_else(|| GgsqlError::ParseError(format!("Missing 'name' field in {}", context)))?;
let value_node = node
.child_by_field_name("value")
.ok_or_else(|| GgsqlError::ParseError(format!("Missing 'value' field in {}", context)))?;
Ok((name_node, value_node))
}
/// Parse a string node, removing quotes and processing escape sequences
fn parse_string_node(node: &Node, source: &SourceTree) -> String {
let text = source.get_text(node);
let unquoted = text.trim_matches(|c| c == '\'' || c == '"');
process_escape_sequences(unquoted)
}
/// Process escape sequences in a string (e.g., \n, \t, \\, \')
fn process_escape_sequences(s: &str) -> String {
let mut result = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '\\' {
match chars.next() {
Some('n') => result.push('\n'),
Some('t') => result.push('\t'),
Some('r') => result.push('\r'),
Some('\\') => result.push('\\'),
Some('\'') => result.push('\''),
Some('"') => result.push('"'),
Some(other) => {
// Unknown escape sequence - keep as-is
result.push('\\');
result.push(other);
}
None => result.push('\\'), // Trailing backslash
}
} else {
result.push(c);
}
}
result
}
/// Parse a number node into f64
fn parse_number_node(node: &Node, source: &SourceTree) -> Result<f64> {
let text = source.get_text(node);
text.parse::<f64>()
.map_err(|e| GgsqlError::ParseError(format!("Failed to parse number '{}': {}", text, e)))
}
/// Parse a boolean node
fn parse_boolean_node(node: &Node, source: &SourceTree) -> bool {
let text = source.get_text(node);
text == "true"
}
/// Parse an array node into Vec<ArrayElement>
fn parse_array_node(node: &Node, source: &SourceTree) -> Result<Vec<ArrayElement>> {
let mut values = Vec::new();
// Find all array_element nodes
let query = "(array_element) @elem";
let array_elements = source.find_nodes(node, query);
for array_element in array_elements {
// array_element is a choice node, so it has exactly one child
let elem_child = array_element.child(0).ok_or_else(|| {
GgsqlError::ParseError("Invalid array_element: missing child".to_string())
})?;
let value = match elem_child.kind() {
"string" => ArrayElement::String(parse_string_node(&elem_child, source)),
"number" => ArrayElement::Number(parse_number_node(&elem_child, source)?),
"boolean" => ArrayElement::Boolean(parse_boolean_node(&elem_child, source)),
"null_literal" => ArrayElement::Null,
_ => {
return Err(GgsqlError::ParseError(format!(
"Invalid array element type: {}",
elem_child.kind()
)));
}
};
values.push(value);
}
Ok(values)
}
/// Parse a value node directly (string, number, boolean, array, or null)
fn parse_value_node(node: &Node, source: &SourceTree, context: &str) -> Result<ParameterValue> {
match node.kind() {
"string" => {
let value = parse_string_node(node, source);
Ok(ParameterValue::String(value))
}
"number" => {
let num = parse_number_node(node, source)?;
Ok(ParameterValue::Number(num))
}
"boolean" => {
let bool_val = parse_boolean_node(node, source);
Ok(ParameterValue::Boolean(bool_val))
}
"array" => {
let values = parse_array_node(node, source)?;
Ok(ParameterValue::Array(values))
}
"null_literal" => Ok(ParameterValue::Null),
_ => Err(GgsqlError::ParseError(format!(
"Unexpected {} value type: {}",
context,
node.kind()
))),
}
}
/// Parse a data source node (identifier or string file path)
fn parse_data_source(node: &Node, source: &SourceTree) -> DataSource {
match node.kind() {
"string" => {
let path = parse_string_node(node, source);
DataSource::FilePath(path)
}
_ => {
let text = source.get_text(node);
DataSource::Identifier(text)
}
}
}
/// Parse a literal_value node into an AestheticValue::Literal
fn parse_literal_value(node: &Node, source: &SourceTree) -> Result<AestheticValue> {
// literal_value is a choice(), so it has exactly one child
let child = node.child(0).unwrap();
let value = parse_value_node(&child, source, "literal")?;
// Grammar ensures literals can't be arrays or nulls, but add safety check
if matches!(value, ParameterValue::Array(_) | ParameterValue::Null) {
return Err(GgsqlError::ParseError(
"Arrays and null cannot be used as literal values in aesthetic mappings".to_string(),
));
}
Ok(AestheticValue::Literal(value))
}
// ============================================================================
// AST Building
// ============================================================================
/// Build a Plot struct from a tree-sitter parse tree
pub fn build_ast(source: &SourceTree) -> Result<Vec<Plot>> {
let root = source.root();
// Check if root is a query node
if root.kind() != "query" {
return Err(GgsqlError::ParseError(format!(
"Expected 'query' root node, got '{}'",
root.kind()
)));
}
// Extract SQL portion node (if exists)
let query = "(sql_portion) @sql";
let sql_portion_node = source.find_node(&root, query);
// Check if last SQL statement is SELECT
let last_is_select = if let Some(sql_node) = sql_portion_node {
check_last_statement_is_select(&sql_node, source)
} else {
false
};
// Find all visualise_statement nodes
let query = "(visualise_statement) @viz";
let viz_nodes = source.find_nodes(&root, query);
let mut specs = Vec::new();
for viz_node in viz_nodes {
let spec = build_visualise_statement(&viz_node, source)?;
// Validate VISUALISE FROM usage
if spec.source.is_some() && last_is_select {
return Err(GgsqlError::ParseError(
"Cannot use VISUALISE FROM when the last SQL statement is SELECT. \
Use either 'SELECT ... VISUALISE' or remove the SELECT and use \
'VISUALISE FROM ...'."
.to_string(),
));
}
specs.push(spec);
}
if specs.is_empty() {
return Err(GgsqlError::ParseError(
"No VISUALISE statements found in query".to_string(),
));
}
Ok(specs)
}
/// Build a single Plot from a visualise_statement node
fn build_visualise_statement(node: &Node, source: &SourceTree) -> Result<Plot> {
let mut spec = Plot::new();
// Walk through children of visualise_statement
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"VISUALISE" | "VISUALIZE" | "FROM" => {
// Skip keywords
continue;
}
"global_mapping" => {
// Parse global mapping (may include wildcard and/or explicit mappings)
spec.global_mappings = parse_mapping(&child, source)?;
}
"wildcard_mapping" => {
// Handle standalone wildcard (*) mapping
spec.global_mappings.wildcard = true;
}
"from_clause" => {
// Extract the 'table' field from table_ref (grammar: FROM table_ref)
let query = "(table_ref table: (_) @table)";
if let Some(table_node) = source.find_node(&child, query) {
spec.source = Some(parse_data_source(&table_node, source));
}
}
"viz_clause" => {
// Process visualization clause
process_viz_clause(&child, source, &mut spec)?;
}
_ => {
// Unknown node type - skip for now
continue;
}
}
}
// Resolve coord (infer from mappings if not explicit)
// This must happen after parsing but before initialize_aesthetic_context()
let layer_mappings: Vec<&Mappings> = spec.layers.iter().map(|l| &l.mappings).collect();
if let Some(inferred) = resolve_coord(
spec.project.as_ref(),
&spec.global_mappings,
&layer_mappings,
)
.map_err(GgsqlError::ParseError)?
{
spec.project = Some(inferred);
}
// Initialize aesthetic context based on coord and facet
// This must happen after all clauses are processed (especially PROJECT and FACET)
spec.initialize_aesthetic_context();
// Transform all aesthetic keys from user-facing (x/y or theta/radius) to internal (pos1/pos2)
// This enables generic handling throughout the pipeline and must happen before merge
// since geom definitions use internal names for their supported/required aesthetics
spec.transform_aesthetics_to_internal();
Ok(spec)
}
/// Process a visualization clause node
fn process_viz_clause(node: &Node, source: &SourceTree, spec: &mut Plot) -> Result<()> {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"draw_clause" => {
let layer = build_layer(&child, source)?;
spec.layers.push(layer);
}
"scale_clause" => {
let scale = build_scale(&child, source)?;
spec.scales.push(scale);
}
"facet_clause" => {
spec.facet = Some(build_facet(&child, source)?);
}
"project_clause" => {
spec.project = Some(build_project(&child, source)?);
}
"label_clause" => {
let new_labels = build_labels(&child, source)?;
// Merge with existing labels if any
if let Some(ref mut existing_labels) = spec.labels {
for (key, value) in new_labels.labels {
existing_labels.labels.insert(key, value);
}
} else {
spec.labels = Some(new_labels);
}
}
"theme_clause" => {
spec.theme = Some(build_theme(&child, source)?);
}
_ => {
// Unknown clause type
continue;
}
}
}
Ok(())
}
// ============================================================================
// Mapping Building
// ============================================================================
/// Parse mapping elements from a node containing mappings and return a Mappings struct
/// Used by global_mapping (VISUALISE), mapping_clause (MAPPING), and remapping_clause (REMAPPING)
/// Tree-sitter recursively finds mapping_element nodes within the nested mapping_list
fn parse_mapping(node: &Node, source: &SourceTree) -> Result<Mappings> {
let mut mappings = Mappings::new();
// Find all mapping_element nodes (recursively searches within mapping_list if present)
let query = "(mapping_element) @elem";
let mapping_nodes = source.find_nodes(node, query);
for mapping_node in mapping_nodes {
parse_mapping_element(&mapping_node, source, &mut mappings)?;
}
Ok(mappings)
}
/// Parse a mapping_element: wildcard, explicit, or implicit mapping
/// Shared by both global (VISUALISE) and layer (MAPPING) mappings
fn parse_mapping_element(node: &Node, source: &SourceTree, mappings: &mut Mappings) -> Result<()> {
// mapping_element is a choice node, so it has exactly one child
let child = node.child(0).ok_or_else(|| {
GgsqlError::ParseError("Invalid mapping_element: missing child".to_string())
})?;
match child.kind() {
"wildcard_mapping" => {
mappings.wildcard = true;
}
"explicit_mapping" => {
let (aesthetic, value) = parse_explicit_mapping(&child, source)?;
mappings.insert(normalise_aes_name(&aesthetic), value);
}
"implicit_mapping" | "identifier" => {
let name = source.get_text(&child);
mappings.insert(
normalise_aes_name(&name),
AestheticValue::standard_column(&name),
);
}
_ => {
return Err(GgsqlError::ParseError(format!(
"Invalid mapping_element child type: {}",
child.kind()
)));
}
}
Ok(())
}
/// Parse an explicit_mapping node (value AS aesthetic)
/// Returns (aesthetic_name, value)
fn parse_explicit_mapping(node: &Node, source: &SourceTree) -> Result<(String, AestheticValue)> {
// Extract name and value nodes using field-based queries
let (name_node, value_node) = extract_name_value_nodes(node, "explicit mapping")?;
// Parse aesthetic name
let aesthetic = source.get_text(&name_node);
// Parse value (mapping_value has exactly one child: column_reference or literal_value)
let value_child = value_node.child(0).ok_or_else(|| {
GgsqlError::ParseError("Invalid explicit mapping: missing value".to_string())
})?;
let value = match value_child.kind() {
"column_reference" => {
// column_reference is just an identifier wrapper, get its text directly
AestheticValue::standard_column(source.get_text(&value_child))
}
"literal_value" => parse_literal_value(&value_child, source)?,
_ => {
return Err(GgsqlError::ParseError(format!(
"Invalid explicit mapping value type: {}",
value_child.kind()
)));
}
};
Ok((aesthetic, value))
}
// ============================================================================
// Layer Building
// ============================================================================
/// Build a Layer from a draw_clause node
/// Syntax: DRAW geom [MAPPING col AS x, ... [FROM source]] [REMAPPING stat AS aes, ...] [SETTING param => val, ...] [PARTITION BY col, ...] [FILTER condition]
fn build_layer(node: &Node, source: &SourceTree) -> Result<Layer> {
let mut geom = Geom::point(); // default
let mut aesthetics = Mappings::new();
let mut remappings = Mappings::new();
let mut parameters = HashMap::new();
let mut partition_by = Vec::new();
let mut filter = None;
let mut order_by = None;
let mut layer_source = None;
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"geom_type" => {
let geom_text = source.get_text(&child);
geom = parse_geom_type(&geom_text)?;
}
"mapping_clause" => {
// Parse aesthetic mappings and optional data source
aesthetics = parse_mapping(&child, source)?;
layer_source = child
.child_by_field_name("layer_source")
.map(|src| parse_data_source(&src, source));
}
"remapping_clause" => {
// Parse stat result remappings (same syntax as mapping_clause)
remappings = parse_mapping(&child, source)?;
}
"setting_clause" => {
parameters = parse_setting_clause(&child, source)?;
}
"partition_clause" => {
partition_by = parse_partition_clause(&child, source)?;
}
"filter_clause" => {
filter = Some(parse_filter_clause(&child, source)?);
}
"order_clause" => {
order_by = Some(parse_order_clause(&child, source)?);
}
_ => {
// Skip keywords and punctuation
continue;
}
}
}
let mut layer = Layer::new(geom);
layer.mappings = aesthetics;
layer.remappings = remappings;
layer.parameters = parameters;
layer.partition_by = partition_by;
layer.filter = filter;
layer.order_by = order_by;
layer.source = layer_source;
Ok(layer)
}
/// Parse a setting_clause: SETTING param => value, ...
fn parse_setting_clause(
node: &Node,
source: &SourceTree,
) -> Result<HashMap<String, ParameterValue>> {
let mut parameters = HashMap::new();
// Find all parameter_assignment nodes
let query = "(parameter_assignment) @param";
let param_nodes = source.find_nodes(node, query);
for param_node in param_nodes {
let (param, mut value) = parse_parameter_assignment(¶m_node, source)?;
if is_color_aesthetic(¶m) {
if let ParameterValue::String(color) = value {
value =
ParameterValue::String(color_to_hex(&color).map_err(GgsqlError::ParseError)?);
}
}
parameters.insert(param, value);
}
Ok(parameters)
}
/// Parse a parameter_assignment: param => value
fn parse_parameter_assignment(
node: &Node,
source: &SourceTree,
) -> Result<(String, ParameterValue)> {
// Extract name and value nodes using field-based queries
let (name_node, value_node) = extract_name_value_nodes(node, "parameter assignment")?;
// Parse parameter name (parameter_name is just an identifier)
let param_name = source.get_text(&name_node);
// Parse parameter value (parameter_value wraps the actual value node)
let param_value = if let Some(value_child) = value_node.child(0) {
parse_value_node(&value_child, source, "parameter")?
} else {
return Err(GgsqlError::ParseError(
"Invalid parameter assignment: empty parameter_value".to_string(),
));
};
Ok((param_name, param_value))
}
/// Parse a partition_clause: PARTITION BY col1, col2, ...
fn parse_partition_clause(node: &Node, source: &SourceTree) -> Result<Vec<String>> {
let query = r#"
(partition_columns
(identifier) @col)
"#;
Ok(source.find_texts(node, query))
}
/// Parse a filter_clause: FILTER <raw SQL expression>
///
/// Extracts the raw SQL text from the filter_expression and returns it verbatim.
/// This allows any valid SQL WHERE expression to be passed to the database backend.
fn parse_filter_clause(node: &Node, source: &SourceTree) -> Result<SqlExpression> {
let query = "(filter_expression) @expr";
if let Some(filter_text) = source.find_text(node, query) {
Ok(SqlExpression::new(filter_text.trim().to_string()))
} else {
Err(GgsqlError::ParseError(
"Could not find filter expression in filter clause".to_string(),
))
}
}
/// Parse an order_clause: ORDER BY date ASC, value DESC
fn parse_order_clause(node: &Node, source: &SourceTree) -> Result<SqlExpression> {
let query = "(order_expression) @expr";
if let Some(order_text) = source.find_text(node, query) {
Ok(SqlExpression::new(order_text.trim().to_string()))
} else {
Err(GgsqlError::ParseError(
"Could not find order expression in order clause".to_string(),
))
}
}
/// Parse a geom_type node text into a Geom
fn parse_geom_type(text: &str) -> Result<Geom> {
match text.to_lowercase().as_str() {
"point" => Ok(Geom::point()),
"line" => Ok(Geom::line()),
"path" => Ok(Geom::path()),
"bar" => Ok(Geom::bar()),
"area" => Ok(Geom::area()),
"rect" => Ok(Geom::rect()),
"polygon" => Ok(Geom::polygon()),
"ribbon" => Ok(Geom::ribbon()),
"histogram" => Ok(Geom::histogram()),
"density" => Ok(Geom::density()),
"smooth" => Ok(Geom::smooth()),
"boxplot" => Ok(Geom::boxplot()),
"violin" => Ok(Geom::violin()),
"text" => Ok(Geom::text()),
"label" => Ok(Geom::label()),
"segment" => Ok(Geom::segment()),
"arrow" => Ok(Geom::arrow()),
"hline" => Ok(Geom::hline()),
"vline" => Ok(Geom::vline()),
"abline" => Ok(Geom::abline()),
"errorbar" => Ok(Geom::errorbar()),
_ => Err(GgsqlError::ParseError(format!(
"Unknown geom type: {}",
text
))),
}
}
// ============================================================================
// Scale Building
// ============================================================================
/// Build a Scale from a scale_clause node
/// SCALE [TYPE] aesthetic [FROM ...] [TO ...] [VIA ...] [SETTING ...] [RENAMING ...]
fn build_scale(node: &Node, source: &SourceTree) -> Result<Scale> {
let mut aesthetic = String::new();
let mut scale_type: Option<ScaleType> = None;
let mut input_range: Option<Vec<ArrayElement>> = None;
let mut explicit_input_range = false;
let mut output_range: Option<OutputRange> = None;
let mut transform: Option<Transform> = None;
let mut explicit_transform = false;
let mut properties = HashMap::new();
let mut label_mapping: Option<HashMap<String, Option<String>>> = None;
let mut label_template = "{}".to_string();
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"SCALE" | "SETTING" | "=>" | "," | "FROM" | "TO" | "VIA" | "RENAMING" => continue, // Skip keywords
"scale_type_identifier" => {
// Parse scale type: CONTINUOUS, DISCRETE, BINNED, DATE, DATETIME
let type_text = source.get_text(&child);
scale_type = Some(parse_scale_type_identifier(&type_text)?);
}
"aesthetic_name" => {
aesthetic = normalise_aes_name(&source.get_text(&child));
}
"scale_from_clause" => {
// Parse FROM [array] -> input_range
input_range = Some(parse_scale_from_clause(&child, source)?);
// Mark as explicit input range (user specified FROM clause)
explicit_input_range = true;
}
"scale_to_clause" => {
// Parse TO [array | identifier] -> output_range
output_range = Some(parse_scale_to_clause(&child, source)?);
}
"scale_via_clause" => {
// Parse VIA identifier -> transform
transform = Some(parse_scale_via_clause(&child, source)?);
// Mark as explicit transform (user specified VIA clause)
explicit_transform = true;
}
"setting_clause" => {
// Reuse existing setting_clause parser
properties = parse_setting_clause(&child, source)?;
}
"scale_renaming_clause" => {
// Parse RENAMING 'A' => 'Alpha', 'B' => 'Beta', * => '{} units'
let (mappings, template) = parse_scale_renaming_clause(&child, source)?;
if !mappings.is_empty() {
label_mapping = Some(mappings);
}
label_template = template;
}
_ => {}
}
}
if aesthetic.is_empty() {
return Err(GgsqlError::ParseError(
"Scale clause missing aesthetic name".to_string(),
));
}
// Replace colour palettes by their hex codes in output_range
if is_color_aesthetic(&aesthetic) {
if let Some(OutputRange::Array(ref elements)) = output_range {
let hex_codes: Vec<ArrayElement> = elements
.iter()
.map(|elem| {
if let ArrayElement::String(color) = elem {
color_to_hex(color).map(ArrayElement::String)
} else {
Ok(elem.clone())
}
})
.collect::<std::result::Result<Vec<_>, _>>()
.map_err(GgsqlError::ParseError)?;
output_range = Some(OutputRange::Array(hex_codes));
}
}
// Validate facet aesthetics cannot have output ranges (TO clause)
// Note: This check uses user-facing names since we're in the parser, before transformation
if is_user_facet_aesthetic(&aesthetic) && output_range.is_some() {
return Err(GgsqlError::ValidationError(format!(
"SCALE {}: facet variables cannot have output ranges (TO clause)",
aesthetic
)));
}
Ok(Scale {
aesthetic,
scale_type,
input_range,
explicit_input_range,
output_range,
transform,
explicit_transform,
properties,
resolved: false,
label_mapping,
label_template,
})
}
/// Parse scale type identifier (CONTINUOUS, DISCRETE, BINNED, ORDINAL, IDENTITY)
fn parse_scale_type_identifier(text: &str) -> Result<ScaleType> {
match text.to_lowercase().as_str() {
"continuous" => Ok(ScaleType::continuous()),
"discrete" => Ok(ScaleType::discrete()),
"binned" => Ok(ScaleType::binned()),
"ordinal" => Ok(ScaleType::ordinal()),
"identity" => Ok(ScaleType::identity()),
_ => Err(GgsqlError::ParseError(format!(
"Unknown scale type: '{}'. Valid types: continuous, discrete, binned, ordinal, identity",
text
))),
}
}
/// Parse FROM clause: FROM [array]
fn parse_scale_from_clause(node: &Node, source: &SourceTree) -> Result<Vec<ArrayElement>> {
let query = "(array) @arr";
let array_node = source
.find_node(node, query)
.ok_or_else(|| GgsqlError::ParseError("FROM clause missing array".to_string()))?;
parse_array_node(&array_node, source)
}
/// Parse TO clause: TO [array | identifier]
fn parse_scale_to_clause(node: &Node, source: &SourceTree) -> Result<OutputRange> {
// Try array first
let array_query = "(array) @arr";
if let Some(array_node) = source.find_node(node, array_query) {
let elements = parse_array_node(&array_node, source)?;
return Ok(OutputRange::Array(elements));
}
// Try identifier (palette name)
let ident_query = "[(identifier) (bare_identifier) (quoted_identifier)] @id";
if let Some(ident_node) = source.find_node(node, ident_query) {
let palette_name = source.get_text(&ident_node);
return Ok(OutputRange::Palette(palette_name));
}
Err(GgsqlError::ParseError(
"TO clause must contain either an array or identifier".to_string(),
))
}
/// Parse VIA clause: VIA identifier
fn parse_scale_via_clause(node: &Node, source: &SourceTree) -> Result<Transform> {
let query = "[(identifier) (bare_identifier) (quoted_identifier)] @id";
let ident_node = source.find_node(node, query).ok_or_else(|| {
GgsqlError::ParseError("VIA clause missing transform identifier".to_string())
})?;
let transform_name = source.get_text(&ident_node);
Transform::from_name(&transform_name).ok_or_else(|| {
GgsqlError::ParseError(format!(
"Unknown transform: '{}'. Valid transforms are: {}",
transform_name,
crate::plot::scale::ALL_TRANSFORM_NAMES.join(", ")
))
})
}
/// Parse RENAMING clause: RENAMING 'A' => 'Alpha', 'B' => 'Beta', 'internal' => NULL, * => '{} units'
///
/// Returns a tuple of:
/// - HashMap where: Key = original value, Value = Some(label) or None for suppressed labels
/// - Template string for wildcard mappings (* => '...'), defaults to "{}"
fn parse_scale_renaming_clause(
node: &Node,
source: &SourceTree,
) -> Result<(HashMap<String, Option<String>>, String)> {
let mut mappings = HashMap::new();
let mut template = "{}".to_string();
// Find all renaming_assignment nodes
let query = "(renaming_assignment) @assign";
let assignment_nodes = source.find_nodes(node, query);
for assignment_node in assignment_nodes {
// Extract name and value nodes using field-based queries
let (name_node, value_node) = extract_name_value_nodes(&assignment_node, "scale renaming")?;
// Check if 'name' is a wildcard
let is_wildcard = name_node.kind() == "*";
// Parse 'name' (from) value - wildcards, strings need unquoting, numbers are raw
let from_value = match name_node.kind() {
"*" => "*".to_string(),
"string" => parse_string_node(&name_node, source),
"number" => source.get_text(&name_node),
"null_literal" => "null".to_string(), // null key for renaming null values
_ => {
return Err(GgsqlError::ParseError(format!(
"Invalid 'from' type in scale renaming: {}",
name_node.kind()
)));
}
};
// Parse 'value' (to) - string or NULL
let to_value: Option<String> = match value_node.kind() {
"string" => Some(parse_string_node(&value_node, source)),
"null_literal" => None, // NULL suppresses the label
_ => {
return Err(GgsqlError::ParseError(format!(
"Invalid 'to' type in scale renaming: {}",
value_node.kind()
)));
}
};
if is_wildcard {
// Wildcard: * => 'template'
if let Some(tmpl) = to_value {
template = tmpl;
}
} else {
// Explicit mapping: 'A' => 'Alpha' or '10' => 'Ten'
mappings.insert(from_value, to_value);
}
}
Ok((mappings, template))
}
// ============================================================================
// Facet Building
// ============================================================================
/// Build a Facet from a facet_clause node
///
/// FACET vars [BY vars] [SETTING ...]
/// - Single variable = wrap layout (no WRAP keyword needed)
/// - BY clause = grid layout
fn build_facet(node: &Node, source: &SourceTree) -> Result<Facet> {
let mut row_vars = Vec::new();
let mut column_vars = Vec::new();
let mut properties = HashMap::new();
let mut cursor = node.walk();
let mut next_vars_are_cols = false;
for child in node.children(&mut cursor) {
match child.kind() {
"FACET" => continue,
"facet_by" => {
next_vars_are_cols = true;
}
"facet_vars" => {
// Parse list of variable names
let vars = parse_facet_vars(&child, source)?;
if next_vars_are_cols {
column_vars = vars;
} else {
row_vars = vars;
}
}
"setting_clause" => {
// Reuse existing setting_clause parser
properties = parse_setting_clause(&child, source)?;
}
_ => {}
}
}
// Determine layout variant: if column_vars is empty, it's a wrap layout
let layout = if column_vars.is_empty() {
FacetLayout::Wrap {
variables: row_vars,
}
} else {
FacetLayout::Grid {
row: row_vars,
column: column_vars,
}
};
Ok(Facet {
layout,
properties,
resolved: false,
})
}
/// Parse facet variables from a facet_vars node
fn parse_facet_vars(node: &Node, source: &SourceTree) -> Result<Vec<String>> {
let query = "(identifier) @var";
Ok(source.find_texts(node, query))
}
// ============================================================================
// Project Building
// ============================================================================
/// Build a Projection from a project_clause node
///
/// Parses the new PROJECT syntax:
/// ```text
/// PROJECT [aesthetic, ...] TO coord_type [SETTING prop => value, ...]
/// ```
///
/// Aesthetics are optional and default to the coord's standard names.
fn build_project(node: &Node, source: &SourceTree) -> Result<Projection> {
let mut coord = Coord::cartesian();
let mut properties = HashMap::new();
let mut user_aesthetics: Option<Vec<String>> = None;
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"PROJECT" | "SETTING" | "TO" | "=>" | "," => continue,
"project_aesthetics" => {
let query = "(identifier) @aes";
user_aesthetics = Some(source.find_texts(&child, query));
}
"project_type" => {
coord = parse_coord_system(&child, source)?;
}
"project_properties" => {
// Find all project_property nodes
let query = "(project_property) @prop";
let prop_nodes = source.find_nodes(&child, query);
for prop_node in prop_nodes {
let (prop_name, prop_value) =
parse_single_project_property(&prop_node, source)?;
properties.insert(prop_name, prop_value);
}
}
_ => {}
}
}
// Resolve aesthetics: use provided or fall back to coord defaults
let aesthetics = if let Some(aes) = user_aesthetics {
// Validate aesthetic count matches coord requirements
let expected = coord.positional_aesthetic_names().len();
if aes.len() != expected {
return Err(GgsqlError::ParseError(format!(
"PROJECT {} requires {} aesthetics, got {}",
coord.name(),
expected,
aes.len()
)));
}
// Validate no conflicts with non-positional or facet aesthetics
validate_positional_aesthetic_names(&aes)?;
aes
} else {
// Use coord defaults - resolved immediately at build time
coord
.positional_aesthetic_names()
.iter()
.map(|s| s.to_string())
.collect()
};
// Validate properties for this coord type
validate_project_properties(&coord, &properties)?;
Ok(Projection {
coord,
aesthetics,
properties,
})
}
/// Validate that positional aesthetic names don't conflict with reserved names
fn validate_positional_aesthetic_names(names: &[String]) -> Result<()> {
use crate::plot::aesthetic::{NON_POSITIONAL, USER_FACET_AESTHETICS};
for name in names {
// Check against non-positional aesthetics
if NON_POSITIONAL.contains(&name.as_str()) {
return Err(GgsqlError::ParseError(format!(
"PROJECT aesthetic '{}' conflicts with non-positional aesthetic. \
Choose a different name.",
name
)));
}