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
use {
    std::{
        collections::{BTreeMap, HashSet, HashMap},
        cell::{Cell, RefCell},
    },
    crate::{
        makepad_error_log::*,
        makepad_live_compiler::*,
        makepad_live_id::*,
        shader_ast::*,
        analyse::*,
        shader_parser::{ShaderParser, ShaderParserDep},
        builtin::{Builtin, generate_builtins},
    }
};


pub struct ShaderRegistry {
    pub all_fns: HashMap<FnPtr, FnDef>,
    pub draw_shader_defs: HashMap<DrawShaderPtr, DrawShaderDef>,
    pub structs: HashMap<StructPtr, StructDef>,
    pub builtins: HashMap<Ident, Builtin>,
    pub enums: HashMap<LiveType, ShaderEnum>,
}

pub struct ShaderEnum {
    pub enum_name: LiveId,
    pub variants: Vec<LiveId>
}

impl ShaderRegistry {
    pub fn new() -> Self {
        Self {
            structs: HashMap::new(),
            enums: HashMap::new(),
            draw_shader_defs: HashMap::new(),
            all_fns: HashMap::new(),
            builtins: generate_builtins()
        }
    }
}

#[derive(Debug)]
pub enum LiveNodeFindResult {
    NotFound,
    Component(LivePtr),
    Struct(StructPtr),
    Function(FnPtr),
    PossibleStatic(StructPtr, FnPtr),
    LiveValue(ValuePtr, TyLit),
    Error(LiveError)
}

pub enum DrawShaderQuery {
    DrawShader,
    Geometry,
}

impl ShaderRegistry {
    
    pub fn flush_registry(&mut self){
        self.all_fns.clear();
        self.draw_shader_defs.clear();
        self.structs.clear();
    }
    
    pub fn register_enum(&mut self, live_type: LiveType, shader_enum: ShaderEnum) {
        self.enums.insert(live_type, shader_enum);
    }
    
    pub fn compute_const_table(&self, draw_shader_ptr: DrawShaderPtr/*, filter_file_id: LiveFileId*/) -> DrawShaderConstTable {
        
        let draw_shader_def = self.draw_shader_defs.get(&draw_shader_ptr).unwrap();
        
        let mut offsets = BTreeMap::new();
        let mut table = Vec::new();
        let mut offset = 0;
        let mut table_index = BTreeMap::new();
        
        for callee in draw_shader_def.all_fns.borrow().iter() {
            let fn_decl = self.all_fns.get(callee).unwrap();
            //if fn_decl.span.file_id == filter_file_id {
            let sub_table = fn_decl.const_table.borrow();
            table.extend(sub_table.as_ref().unwrap().iter());
            
            for ct_span in fn_decl.const_table_spans.borrow().as_ref().unwrap().iter() {
                table_index.insert(
                    ct_span.token_id,
                    ConstTableItem {
                        offset: offset + ct_span.offset,
                        slots: ct_span.slots
                    }
                );
            }
            offsets.insert(*callee, offset);
            offset += sub_table.as_ref().unwrap().len();
        }
        
        let size = table.len();
        let align_gap = 4 - (size - ((size >> 2) << 2));
        for _ in 0..align_gap {
            table.push(0.0);
        }
        DrawShaderConstTable {
            table,
            offsets,
            table_index
        }
    }
    
    pub fn fn_ident_from_ptr(&self, live_registry: &LiveRegistry, fn_node_ptr: FnPtr) -> Ident {
        let node = live_registry.ptr_to_node(fn_node_ptr.0);
        Ident(node.id)
    }
    
    pub fn draw_shader_method_ptr_from_ident(&self, draw_shader_def: &DrawShaderDef, ident: Ident) -> Option<FnPtr> {
        for fn_node_ptr in &draw_shader_def.methods {
            let fn_decl = self.all_fns.get(fn_node_ptr).unwrap();
            if fn_decl.ident == ident {
                return Some(*fn_node_ptr);
            }
        }
        None
    }
    
    pub fn struct_method_ptr_from_ident(&self, struct_def: &StructDef, ident: Ident) -> Option<FnPtr> {
        for fn_node_ptr in &struct_def.methods {
            let fn_decl = self.all_fns.get(fn_node_ptr).unwrap();
            if fn_decl.ident == ident {
                return Some(*fn_node_ptr);
            }
        }
        None
    }
    
    pub fn draw_shader_method_decl_from_ident(&self, draw_shader_def: &DrawShaderDef, ident: Ident) -> Option<&FnDef> {
        for fn_node_ptr in &draw_shader_def.methods {
            let fn_decl = self.all_fns.get(fn_node_ptr).unwrap();
            if fn_decl.ident == ident {
                return Some(fn_decl)
            }
        }
        None
    }
    
    pub fn struct_method_decl_from_ident(&self, struct_def: &StructDef, ident: Ident) -> Option<&FnDef> {
        for fn_node_ptr in &struct_def.methods {
            let fn_decl = self.all_fns.get(fn_node_ptr).unwrap();
            if fn_decl.ident == ident {
                return Some(fn_decl)
            }
        }
        None
    }
    
    pub fn find_live_node_by_path(&self, live_registry: &LiveRegistry, base_ptr: LivePtr, ids: &[LiveId]) -> LiveNodeFindResult {
        
        let doc = &live_registry.ptr_to_doc(base_ptr);
        
        let ret = walk_recur(live_registry, None, base_ptr.file_id, base_ptr.generation, base_ptr.index as usize, &doc.nodes, ids);
        return ret;
        // ok so we got a node. great. now what
        fn walk_recur(live_registry: &LiveRegistry, struct_ptr: Option<LivePtr>, file_id: LiveFileId, generation:LiveFileGeneration, index: usize, nodes: &[LiveNode], ids: &[LiveId]) -> LiveNodeFindResult {
            let node = &nodes[index];
            
            if ids.len() != 0 && !node.value.is_class() && !node.value.is_clone() && !node.value.is_object() {
                return LiveNodeFindResult::NotFound;
            }
            
            let now_ptr = LivePtr {file_id, index: index as u32, generation};
            //let first_def = node.origin.first_def().unwrap();
            match node.value {
                LiveValue::Bool(_) => {
                    return LiveNodeFindResult::LiveValue(ValuePtr(now_ptr), TyLit::Bool)
                },
                LiveValue::Int64(_)=> {
                    return LiveNodeFindResult::LiveValue(ValuePtr(now_ptr), TyLit::Int)
                }
                LiveValue::Float32(_)  => {
                    return LiveNodeFindResult::LiveValue(ValuePtr(now_ptr), TyLit::Float)
                }
                LiveValue::Float64(_)  => {
                    return LiveNodeFindResult::LiveValue(ValuePtr(now_ptr), TyLit::Float)
                }
                LiveValue::Color(_)  => {
                    return LiveNodeFindResult::LiveValue(ValuePtr(now_ptr), TyLit::Vec4)
                }
                LiveValue::Vec2(_)  => {
                    return LiveNodeFindResult::LiveValue(ValuePtr(now_ptr), TyLit::Vec2)
                }
                LiveValue::Vec3(_)  => {
                    return LiveNodeFindResult::LiveValue(ValuePtr(now_ptr), TyLit::Vec3)
                }
                LiveValue::Vec4(_) => {
                    return LiveNodeFindResult::LiveValue(ValuePtr(now_ptr), TyLit::Vec4)
                }
                LiveValue::Expr{..} => {
                    // ok lets eval the expr to get a type
                    match live_eval(live_registry, index, &mut (index + 1), nodes){
                        Ok(value) => {
                            if let Some(ty) = Ty::from_live_eval(value){
                                if let Some(ty_lit) = ty.maybe_ty_lit(){
                                    return LiveNodeFindResult::LiveValue(ValuePtr(now_ptr), ty_lit)
                                }
                            }
                            return LiveNodeFindResult::Error(
                                LiveError {
                                    origin: live_error_origin!(),
                                    message: format!("Type of eval result not valid for shader"),
                                    span: nodes[index].origin.token_id().unwrap().into()
                                }
                            );
                        }
                        Err(err)=>{
                            error!("Cannot find node in expression");
                            return LiveNodeFindResult::Error(err)
                        }
                    }
                }
                LiveValue::DSL {token_start, ..} => {
                    // lets get the first token
                    let origin_doc = live_registry.token_id_to_origin_doc(node.origin.token_id().unwrap());
                    match origin_doc.tokens[token_start as usize].token {
                        LiveToken::Ident(live_id!(fn)) => {
                            if let Some(struct_ptr) = struct_ptr {
                                return LiveNodeFindResult::PossibleStatic(StructPtr(struct_ptr), FnPtr(now_ptr));
                            }
                            return LiveNodeFindResult::Function(FnPtr(now_ptr));
                        }
                        _ => LiveNodeFindResult::NotFound
                    }
                }
                LiveValue::Class {..} => {
                    if ids.len() == 0 {
                        return LiveNodeFindResult::Component(now_ptr);
                    }
                    match nodes.child_by_name(index, ids[0].as_instance()) {
                        Some(child_index) => {
                            return walk_recur(live_registry, None, file_id, generation, child_index, nodes, &ids[1..])
                        }
                        None => {
                            return LiveNodeFindResult::NotFound;
                        }
                    }
                }
                LiveValue::Clone(clone) => {
                    if ids.len() == 0 {
                        if clone == live_id!(struct) {
                            return LiveNodeFindResult::Struct(StructPtr(now_ptr));
                        }
                        return LiveNodeFindResult::Component(now_ptr);
                    }
                    match nodes.child_by_name(index, ids[0].as_instance()) {
                        Some(child_index) => {
                            let struct_ptr = if clone == live_id!(struct) {
                                Some(now_ptr)
                            }
                            else {
                                None
                            };
                            return walk_recur(live_registry, struct_ptr, file_id,  generation, child_index, nodes, &ids[1..])
                        }
                        None => {
                            return LiveNodeFindResult::NotFound;
                        }
                    }
                }
                LiveValue::Object => {
                    if ids.len() == 0 {
                        return LiveNodeFindResult::NotFound;
                    }
                    match nodes.child_by_name(index, ids[0].as_instance()) {
                        Some(child_index) => {
                            return walk_recur(live_registry, None, file_id,  generation,  child_index, nodes, &ids[1..])
                        }
                        None => {
                            return LiveNodeFindResult::NotFound;
                        }
                    }
                }
                _ => {
                    return LiveNodeFindResult::NotFound;
                }
            }
        }
    }
    
    pub fn analyse_deps(&mut self, live_registry: &LiveRegistry, deps: &[ShaderParserDep]) -> Result<(), LiveError> {
        // recur on used types
        for dep in deps {
            match dep {
                /*ShaderParserDep::Const(dep) => {
                    self.analyse_const(live_registry, *dep) ?;
                },*/
                ShaderParserDep::Struct(dep) => {
                    self.analyse_struct(live_registry, *dep) ?;
                },
                ShaderParserDep::Function(struct_ptr, fn_ptr) => {
                    self.analyse_plain_fn(live_registry, *struct_ptr, *fn_ptr) ?
                }
            }
        }
        Ok(())
    }
    
    
    // lets compile the thing
    pub fn analyse_plain_fn(&mut self, live_registry: &LiveRegistry, struct_ptr: Option<StructPtr>, fn_ptr: FnPtr) -> Result<(), LiveError> {
        
        if self.all_fns.get(&fn_ptr).is_some() {
            return Ok(());
        }
        // alright lets parse and analyse a plain fn
        let fn_node = live_registry.ptr_to_node(fn_ptr.0);
        match fn_node.value {
            LiveValue::DSL {token_start, token_count, expand_index} => {
                let id = fn_node.id;
                let mut parser_deps = Vec::new();
                // lets parse this thing
                let origin_doc = &live_registry.token_id_to_origin_doc(fn_node.origin.token_id().unwrap());
                
                let parser = ShaderParser::new(
                    live_registry,
                    self,
                    origin_doc.get_tokens(token_start as usize, token_count as usize),
                    &mut parser_deps,
                    if let Some(struct_ptr) = struct_ptr {Some(FnSelfKind::Struct(struct_ptr))}else {None},
                    expand_index.unwrap() as usize,
                    fn_node.origin.token_id().unwrap().file_id().unwrap(),
                    token_start as usize
                    //Some(struct_full_ptr)
                );
                
                let fn_def = parser.expect_plain_fn_def(
                    fn_ptr,
                    Ident(id),
                ) ?;
                self.all_fns.insert(fn_ptr, fn_def);
                
                self.analyse_deps(live_registry, &parser_deps) ?;
                
                // ok analyse the struct methods now.
                let mut fa = FnDefAnalyser {
                    live_registry,
                    closure_return_ty: None,
                    fn_def: self.all_fns.get(&fn_ptr).unwrap(),
                    scopes: &mut Scopes::new(),
                    shader_registry: self,
                    is_inside_loop: false,
                    options: ShaderAnalyseOptions {
                        no_const_collapse: true
                    }
                };
                fa.analyse_fn_decl() ?;
                fa.analyse_fn_def() ?;
                
                Ok(())
            }
            _ => panic!()
        }
    }
    
    
    // lets compile the thing
    pub fn analyse_struct(&mut self, live_registry: &LiveRegistry, struct_ptr: StructPtr) -> Result<(), LiveError> {
        
        if self.structs.get(&struct_ptr).is_some() {
            return Ok(());
        }
        
        let (doc, struct_node) = live_registry.ptr_to_doc_node(struct_ptr.0);
        
        match struct_node.value {
            LiveValue::Clone(clone) => {
                if clone != live_id!(struct) {
                    panic!()
                }
                let mut struct_def = StructDef {
                    span: struct_node.origin.token_id().unwrap().into(),
                    struct_refs: RefCell::new(None),
                    fields: Vec::new(),
                    methods: Vec::new()
                };
                
                let mut parser_deps = Vec::new();
                
                // ok how do we iterate children of this node
                let mut node_iter = doc.nodes.first_child(struct_ptr.node_index());
                while let Some(node_index) = node_iter {
                    let prop_ptr = struct_ptr.with_index(node_index);
                    let prop = &doc.nodes[node_index];
                    
                    match prop.value {
                        LiveValue::DSL {token_start, token_count, expand_index} => {
                            let id = prop.id;
                            let origin_doc = &live_registry.token_id_to_origin_doc(prop.origin.token_id().unwrap());
                            
                            let parser = ShaderParser::new(
                                live_registry,
                                self,
                                origin_doc.get_tokens(token_start as usize, token_count as usize),
                                &mut parser_deps,
                                Some(FnSelfKind::Struct(struct_ptr)),
                                expand_index.unwrap() as usize,
                                prop.origin.token_id().unwrap().file_id().unwrap(),
                                token_start as usize
                                //Some(struct_full_ptr)
                            );
                            match origin_doc.tokens[token_start as usize].token {
                                LiveToken::Ident(live_id!(fn)) => {
                                    
                                    let fn_def = parser.expect_method_def(
                                        FnPtr(prop_ptr),
                                        Ident(id),
                                    ) ?;
                                    // if we get false, this was not a method but could be static.
                                    // statics need a pointer to their struct to resolve Self
                                    // so we can't treat them purely as loose methods
                                    if let Some(fn_def) = fn_def {
                                        struct_def.methods.push(fn_def.fn_ptr);
                                        self.all_fns.insert(fn_def.fn_ptr, fn_def);
                                    }
                                }
                                _ => {
                                    return Err(LiveError {
                                        origin: live_error_origin!(),
                                        span: prop.origin.token_id().unwrap().into(),
                                        message: format!("Unexpected DSL node")
                                    })
                                    /*
                                    let def = parser.expect_field(Ident(id), VarDefPtr(prop_ptr)) ?;
                                    if let Some(def) = def {
                                        struct_def.fields.push(def);
                                    }*/
                                }
                            }
                        },
                        LiveValue::Id(type_name) if live_registry.get_node_prefix(prop.origin) == Some(live_id!(field)) => {
                            // lets fetch the span
                            
                            if let Some(ty_lit) = TyLit::from_id(type_name) {
                                struct_def.fields.push(StructFieldDef {
                                    var_def_ptr: VarDefPtr(prop_ptr),
                                    span:prop.origin.token_id().unwrap().into(),
                                    ident: Ident(prop.id),
                                    ty_expr: ty_lit.to_ty().to_ty_expr()
                                })
                            }
                            else {
                                // TODO support structs as fields here
                                return Err(LiveError {
                                    origin: live_error_origin!(),
                                    span: prop.origin.token_id().unwrap().into(),
                                    message: format!("Type not found for struct field {}", type_name)
                                })
                            }
                        },
                        _ => {
                            return Err(LiveError {
                                origin: live_error_origin!(),
                                span: prop.origin.token_id().unwrap().into(),
                                message: format!("Cannot use {:?} in struct", prop.value)
                            })
                        }
                    }
                    node_iter = doc.nodes.next_child(node_index);
                }
                // we should store the structs
                self.structs.insert(struct_ptr, struct_def);
                
                self.analyse_deps(live_registry, &parser_deps) ?;
                
                // ok analyse the struct methods now.
                let mut sa = StructAnalyser {
                    live_registry,
                    struct_def: self.structs.get(&struct_ptr).unwrap(),
                    scopes: &mut Scopes::new(),
                    shader_registry: self,
                    options: ShaderAnalyseOptions {
                        no_const_collapse: true
                    }
                };
                sa.analyse_struct() ?;
                //println!("STRUCT");
                
            }
            _ => ()
        }
        
        Ok(())
    }
    
    // lets compile the thing
    pub fn analyse_draw_shader<F>(&mut self, live_registry: &LiveRegistry, draw_shader_ptr: DrawShaderPtr, mut ext_self: F) -> Result<(),
        LiveError>
    where F: FnMut(&LiveRegistry, &ShaderRegistry, TokenSpan, DrawShaderQuery, LiveType, &mut DrawShaderDef)
    {
        let mut draw_shader_def = DrawShaderDef::default();
        
        // lets insert the 2D drawshader uniforms
        draw_shader_def.add_uniform(id_lut!(camera_projection), id_lut!(pass), Ty::Mat4, TokenSpan::default());
        draw_shader_def.add_uniform(id_lut!(camera_view), id_lut!(pass), Ty::Mat4, TokenSpan::default());
        draw_shader_def.add_uniform(id_lut!(camera_inv), id_lut!(pass), Ty::Mat4, TokenSpan::default());
        draw_shader_def.add_uniform(id_lut!(dpi_factor), id_lut!(pass), Ty::Float, TokenSpan::default());
        draw_shader_def.add_uniform(id_lut!(dpi_dilate), id_lut!(pass), Ty::Float, TokenSpan::default());
        draw_shader_def.add_uniform(id_lut!(time), id_lut!(pass), Ty::Float, TokenSpan::default());
        draw_shader_def.add_uniform(id_lut!(view_transform), id_lut!(view), Ty::Mat4, TokenSpan::default());
        draw_shader_def.add_uniform(id_lut!(draw_zbias), id_lut!(draw), Ty::Float, TokenSpan::default());
        
        let (doc, class_node) = live_registry.ptr_to_doc_node(draw_shader_ptr.0);

        match &class_node.value {
            LiveValue::Class {live_type, ..} => {
                
                ext_self(
                    live_registry,
                    self,
                    class_node.origin.token_id().unwrap().into(),
                    DrawShaderQuery::DrawShader,
                    *live_type,
                    &mut draw_shader_def
                );
                
                let mut parser_deps = Vec::new();
                
                let mut node_iter = doc.nodes.first_child(draw_shader_ptr.node_index());
                let mut method_set = HashSet::new();
                while let Some(node_index) = node_iter {
                    let prop = &doc.nodes[node_index];
                    let prop_ptr = draw_shader_ptr.with_index(node_index);
                    if prop.id == live_id!(debug_id){
                        node_iter = doc.nodes.next_child(node_index);
                        continue;
                    }
                    match prop.value {
                        LiveValue::Bool(_) |
                        LiveValue::Id(_)  |
                        LiveValue::Int64(_) |
                        LiveValue::Float32(_) |
                        LiveValue::Float64(_) |
                        LiveValue::Color(_) |
                        LiveValue::Vec2(_) |
                        LiveValue::Vec3(_) |
                        LiveValue::Vec4(_) | 
                        LiveValue::Expr{..} => {
                            //let before = live_registry.get_node_prefix(prop.origin);
                            if prop.origin.prop_type() != LivePropType::Field{
                                /*if before == Some(live_id!(const)){
                                    node_iter = doc.nodes.next_child(node_index);
                                    continue;
                                }*/
                                return Err(LiveError {
                                    origin: live_error_origin!(),
                                    span: prop.origin.token_id().unwrap().into(),
                                    message: format!("Can only support field colon : values don't use =")
                                })
                            }
                            if prop.id == live_id!(size){
                                
                            }
                            let first_def = prop.origin.first_def().unwrap();
                            let before = live_registry.get_node_prefix(prop.origin);
                           
                            let ty = match ShaderTy::from_live_node(live_registry, node_index, &doc.nodes){
                                Ok(ty)=>ty,
                                Err(_)=>{
                                    // just ignore it
                                    node_iter = doc.nodes.next_child(node_index);
                                    continue;
                                    //return Err(err)
                                }
                            };
                            let ty_expr = ty.to_ty_expr();
                            match before {
                                Some(live_id!(geometry)) => {
                                    draw_shader_def.fields.push(DrawShaderFieldDef {
                                        kind: DrawShaderFieldKind::Geometry {
                                            is_used_in_pixel_shader: Cell::new(false),
                                            var_def_ptr: Some(VarDefPtr(prop_ptr)),
                                        },
                                        span: first_def.into(),
                                        ident: Ident(prop.id),
                                        ty_expr
                                    });
                                },
                                Some(live_id!(instance)) => {
                                    let decl = DrawShaderFieldDef {
                                        kind: DrawShaderFieldKind::Instance {
                                            is_used_in_pixel_shader: Cell::new(false),
                                            live_field_kind: LiveFieldKind::Live,
                                            var_def_ptr: Some(VarDefPtr(prop_ptr)),
                                        },
                                        span: first_def.into(),
                                        ident: Ident(prop.id),
                                        ty_expr
                                    };
                                    // find from the start the first instancefield
                                    // without a var_def_node_prt
                                    if let Some(index) = draw_shader_def.fields.iter().position( | field | {
                                        if let DrawShaderFieldKind::Instance {var_def_ptr, ..} = field.kind {
                                            if var_def_ptr.is_none() {
                                                return true
                                            }
                                        }
                                        false
                                    }) {
                                        draw_shader_def.fields.insert(index, decl);
                                    }
                                    else {
                                        draw_shader_def.fields.push(decl);
                                    }
                                    
                                },
                                Some(live_id!(uniform)) => {
                                    draw_shader_def.fields.push(DrawShaderFieldDef {
                                        kind: DrawShaderFieldKind::Uniform {
                                            var_def_ptr: Some(VarDefPtr(prop_ptr)),
                                            block_ident: Ident(live_id!(user)),
                                        },
                                        span: first_def.into(),
                                        ident: Ident(prop.id),
                                        ty_expr
                                    });
                                },
                                Some(live_id!(varying)) => {
                                    draw_shader_def.fields.push(DrawShaderFieldDef {
                                        kind: DrawShaderFieldKind::Varying {
                                            var_def_ptr: VarDefPtr(prop_ptr),
                                        },
                                        span: first_def.into(),
                                        ident: Ident(prop.id),
                                        ty_expr
                                    });
                                },
                                Some(live_id!(texture)) => {
                                    draw_shader_def.fields.push(DrawShaderFieldDef {
                                        kind: DrawShaderFieldKind::Texture {
                                            var_def_ptr: Some(VarDefPtr(prop_ptr)),
                                        },
                                        span: first_def.into(),
                                        ident: Ident(prop.id),
                                        ty_expr
                                    });
                                }
                                None => {
                                    if let LiveValue::Bool(val) = prop.value {
                                        match prop.id {
                                            live_id!(debug) => {
                                                draw_shader_def.flags.debug = val;
                                            }
                                            live_id!(draw_call_compare) => {
                                                draw_shader_def.flags.draw_call_nocompare = val;
                                            }
                                            live_id!(draw_call_always) => {
                                                draw_shader_def.flags.draw_call_always = val;
                                            }
                                            _ => {} // could be input value
                                        }
                                    }
                                },
                                _ => {
                                    return Err(LiveError {
                                        origin: live_error_origin!(),
                                        span: first_def.into(),
                                        message: format!("Unexpected variable prefix {:?}", before)
                                    })
                                }
                            };
                        }
                        LiveValue::Class {live_type, ..} => {
                            if prop.id == live_id!(geometry) {
                                ext_self(
                                    live_registry,
                                    self,
                                    prop.origin.token_id().unwrap().into(),
                                    DrawShaderQuery::Geometry,
                                    live_type,
                                    &mut draw_shader_def
                                );
                            }
                        }
                        LiveValue::DSL {token_start, token_count, expand_index} => {
                            let origin_doc = live_registry.token_id_to_origin_doc(prop.origin.token_id().unwrap());
                            
                            let parser = ShaderParser::new(
                                live_registry,
                                self,
                                origin_doc.get_tokens(token_start as usize, token_count as usize),
                                &mut parser_deps,
                                Some(FnSelfKind::DrawShader(draw_shader_ptr)),
                                expand_index.unwrap() as usize,
                                prop.origin.token_id().unwrap().file_id().unwrap(),
                                token_start as usize
                                //None
                            );
                            
                            let token = &origin_doc.tokens[token_start as usize];
                            match token.token {
                                LiveToken::Ident(live_id!(fn)) => {
                                    let fn_def = parser.expect_method_def(
                                        FnPtr(prop_ptr),
                                        Ident(prop.id),
                                    ) ?;
                                    if let Some(fn_def) = fn_def {
                                        method_set.insert(prop.id);
                                        draw_shader_def.methods.push(fn_def.fn_ptr);
                                        self.all_fns.insert(fn_def.fn_ptr, fn_def);
                                    }
                                }
                                _ => {
                                    return Err(LiveError {
                                        origin: live_error_origin!(),
                                        span: token.span.into(),
                                        message: format!("Unexpected in shader body {}", token)
                                    })
                                    /*
                                    let decl = parser.expect_self_decl(Ident(prop.id), prop_ptr) ?;
                                    if let Some(decl) = decl {
                                        // lets see where to inject this.
                                        // if its an instance var it needs to
                                        // go above the var_def_node_ptr one
                                        if let DrawShaderFieldKind::Instance {..} = decl.kind {
                                            // find from the start the first instancefield
                                            // without a var_def_node_prt
                                            if let Some(index) = draw_shader_def.fields.iter().position( | field | {
                                                if let DrawShaderFieldKind::Instance {var_def_ptr, ..} = field.kind {
                                                    if var_def_ptr.is_none() {
                                                        return true
                                                    }
                                                }
                                                false
                                            }) {
                                                draw_shader_def.fields.insert(index, decl);
                                            }
                                            else {
                                                draw_shader_def.fields.push(decl);
                                            }
                                        }
                                        else {
                                            draw_shader_def.fields.push(decl);
                                        }
                                    }*/
                                }
                            }
                            
                        },
                        _ => ()
                    }
                    node_iter = doc.nodes.next_child(node_index);
                }
                // lets check for duplicate fields
                for i in 0..draw_shader_def.fields.len() {
                    for j in (i + 1)..draw_shader_def.fields.len() {
                        let field_a = &draw_shader_def.fields[i];
                        let field_b = &draw_shader_def.fields[j];
                        if field_a.ident == field_b.ident && !field_a.ident.0.is_empty() {
                            //let doc = live_registry.ptr_to_doc(draw_shader_ptr.0);
                            //doc.nodes.to_string(draw_shader_ptr.index as usize,100)
                            
                            return Err(LiveError {
                                origin: live_error_origin!(),
                                span: field_a.span.into(),
                                message: format!("Field double declaration  {}",field_a.ident)
                            })
                        }
                    }
                }
                
                self.draw_shader_defs.insert(draw_shader_ptr, draw_shader_def);
                
                if !method_set.contains(&live_id!(vertex)) {
                    return Err(LiveError {
                        origin: live_error_origin!(),
                        span: class_node.origin.token_id().unwrap().into(),
                        message: format!("analyse_draw_shader missing vertex method")
                    })
                }
                
                if !method_set.contains(&live_id!(pixel)) {
                    return Err(LiveError {
                        origin: live_error_origin!(),
                        span: class_node.origin.token_id().unwrap().into(),
                        message: format!("analyse_draw_shader missing pixel method")
                    })
                }
                
                self.analyse_deps(live_registry, &parser_deps) ?;
                
                let draw_shader_def = self.draw_shader_defs.get(&draw_shader_ptr).unwrap();
                let mut sa = DrawShaderAnalyser {
                    live_registry,
                    shader_registry: self,
                    draw_shader_def: draw_shader_def,
                    scopes: &mut Scopes::new(),
                    options: ShaderAnalyseOptions {
                        no_const_collapse: true
                    }
                };
                sa.analyse_shader() ?;
                // ok we have all structs
                return Ok(())
            }
            x => return Err(LiveError {
                origin: live_error_origin!(),
                span: class_node.origin.token_id().unwrap().into(),
                message: format!("analyse_draw_shader could not find shader class {:?}", x)
            })
        }
    }
    
}