circom-lsp-program-structure 2.1.5

Support crate for circom-lsp
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
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
use crate::{file_definition::{FileLocation, FileID}, error_definition::Report, error_code::{ReportCode}};
use num_bigint::BigInt;
use serde_derive::{Deserialize, Serialize};

#[derive(Clone)]
pub enum Pragma {
    Version(Meta, FileID, Version),
    CustomGates(Meta ,FileID),
    Unrecognized,
}

pub trait FillMeta {
    fn fill(&mut self, file_id: usize, elem_id: &mut usize);
}

pub type MainComponent = (Vec<String>, Expression);
pub fn build_main_component(public: Vec<String>, call: Expression) -> MainComponent {
    (public, call)
}

pub type Version = (usize, usize, usize);

#[derive(Clone)]
pub struct Meta {
    pub elem_id: usize,
    pub start: usize,
    pub end: usize,
    pub location: FileLocation,
    pub file_id: Option<usize>,
    pub component_inference: Option<String>,
    type_knowledge: TypeKnowledge,
    memory_knowledge: MemoryKnowledge,
}
impl Meta {
    pub fn new(start: usize, end: usize) -> Meta {
        Meta {
            end,
            start,
            elem_id: 0,
            location: start..end,
            file_id: Option::None,
            component_inference: None,
            type_knowledge: TypeKnowledge::default(),
            memory_knowledge: MemoryKnowledge::default(),
        }
    }
    pub fn change_location(&mut self, location: FileLocation, file_id: Option<usize>) {
        self.location = location;
        self.file_id = file_id;
    }
    pub fn get_start(&self) -> usize {
        self.location.start
    }
    pub fn get_end(&self) -> usize {
        self.location.end
    }
    pub fn get_file_id(&self) -> usize {
        if let Option::Some(id) = self.file_id {
            id
        } else {
            panic!("Empty file id accessed")
        }
    }
    pub fn get_memory_knowledge(&self) -> &MemoryKnowledge {
        &self.memory_knowledge
    }
    pub fn get_type_knowledge(&self) -> &TypeKnowledge {
        &self.type_knowledge
    }
    pub fn get_mut_memory_knowledge(&mut self) -> &mut MemoryKnowledge {
        &mut self.memory_knowledge
    }
    pub fn get_mut_type_knowledge(&mut self) -> &mut TypeKnowledge {
        &mut self.type_knowledge
    }
    pub fn file_location(&self) -> FileLocation {
        self.location.clone()
    }
    pub fn set_file_id(&mut self, file_id: usize) {
        self.file_id = Option::Some(file_id);
    }
}

#[derive(Clone)]
pub struct AST {
    pub meta: Meta,
    pub compiler_version: Option<Version>,
    pub custom_gates: bool,
    pub custom_gates_declared: bool,
    pub includes: Vec<String>,
    pub definitions: Vec<Definition>,
    pub main_component: Option<MainComponent>,
}

impl AST {
    pub fn new(
        meta: Meta,
        pragmas: Vec<Pragma>,
        includes: Vec<String>,
        definitions: Vec<Definition>,
        main_component: Option<MainComponent>,
    ) -> (AST,Vec<Report>) {
        let mut custom_gates = None;
        let mut compiler_version = None;
        let mut reports = Vec::new();
        for p in pragmas {
            match p {
                // TODO: don't panic
                Pragma::Version(location, file_id, ver) => match compiler_version {
                    Some(_) => reports.push(produce_report(
                            ReportCode::MultiplePragma,location.start..location.end, file_id)),
                    None => compiler_version = Some(ver),
                },
                Pragma::CustomGates(location, file_id ) => match custom_gates {
                    Some(_) => reports.push(produce_report(
                        ReportCode::MultiplePragma, location.start..location.end, file_id)),
                    None => custom_gates = Some(true),
                },
                Pragma::Unrecognized => {}, //This error is previously handled, and the
                                            //parsing continues to catch more parsing errors.
            }
        }

        let custom_gates_declared = definitions.iter().any(|definition| {
            matches!(definition, Definition::Template { is_custom_gate: true, .. })
        });

        (AST {
            meta,
            compiler_version,
            custom_gates: custom_gates.unwrap_or(false),
            custom_gates_declared,
            includes,
            definitions,
            main_component,
        }, reports)
    }
}

#[derive(Clone)]
pub enum Definition {
    Template {
        meta: Meta,
        name: String,
        args: Vec<String>,
        arg_location: FileLocation,
        body: Statement,
        parallel: bool,
        is_custom_gate: bool,
    },
    Function {
        meta: Meta,
        name: String,
        args: Vec<String>,
        arg_location: FileLocation,
        body: Statement,
    },
}
pub fn build_template(
    meta: Meta,
    name: String,
    args: Vec<String>,
    arg_location: FileLocation,
    body: Statement,
    parallel: bool,
    is_custom_gate: bool,
) -> Definition {
    Definition::Template { meta, name, args, arg_location, body, parallel, is_custom_gate }
}

pub fn build_function(
    meta: Meta,
    name: String,
    args: Vec<String>,
    arg_location: FileLocation,
    body: Statement,
) -> Definition {
    Definition::Function { meta, name, args, arg_location, body }
}

#[derive(Clone)]
pub enum Statement {
    IfThenElse {
        meta: Meta,
        cond: Expression,
        if_case: Box<Statement>,
        else_case: Option<Box<Statement>>,
    },
    While {
        meta: Meta,
        cond: Expression,
        stmt: Box<Statement>,
    },
    Return {
        meta: Meta,
        value: Expression,
    },
    InitializationBlock {
        meta: Meta,
        xtype: VariableType,
        initializations: Vec<Statement>,
    },
    Declaration {
        meta: Meta,
        xtype: VariableType,
        name: String,
        dimensions: Vec<Expression>,
        is_constant: bool,
    },
    Substitution {
        meta: Meta,
        var: String,
        access: Vec<Access>,
        op: AssignOp,
        rhe: Expression,
    },
    MultSubstitution {
        meta: Meta,
        lhe: Expression,
        op: AssignOp,
        rhe: Expression,
    },
    UnderscoreSubstitution{
        meta: Meta,
        op: AssignOp,
        rhe: Expression,
    },
    ConstraintEquality {
        meta: Meta,
        lhe: Expression,
        rhe: Expression,
    },
    LogCall {
        meta: Meta,
        args: Vec<LogArgument>,
    },
    Block {
        meta: Meta,
        stmts: Vec<Statement>,
    },
    Assert {
        meta: Meta,
        arg: Expression,
    },
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum SignalType {
    Output,
    Input,
    Intermediate,
}

pub type TagList = Vec<String>;

#[derive(Clone, PartialEq, Ord, PartialOrd, Eq)]
pub enum VariableType {
    Var,
    Signal(SignalType, TagList),
    Component,
    AnonymousComponent,
}

#[derive(Clone)]
pub enum Expression {
    InfixOp {
        meta: Meta,
        lhe: Box<Expression>,
        infix_op: ExpressionInfixOpcode,
        rhe: Box<Expression>,
    },
    PrefixOp {
        meta: Meta,
        prefix_op: ExpressionPrefixOpcode,
        rhe: Box<Expression>,
    },
    InlineSwitchOp {
        meta: Meta,
        cond: Box<Expression>,
        if_true: Box<Expression>,
        if_false: Box<Expression>,
    },
    ParallelOp {
        meta: Meta,
        rhe: Box<Expression>,
    },
    Variable {
        meta: Meta,
        name: String,
        access: Vec<Access>,
    },
    Number(Meta, BigInt),
    Call {
        meta: Meta,
        id: String,
        args: Vec<Expression>,
    },
    AnonymousComp{
        meta: Meta,
        id: String,
        is_parallel: bool,
        params: Vec<Expression>,
        signals: Vec<Expression>,
        names: Option<Vec<(AssignOp,String)>>,
    },
    ArrayInLine {
        meta: Meta,
        values: Vec<Expression>,
    },
    Tuple {
        meta: Meta,
        values: Vec<Expression>,
    },
    UniformArray {
        meta: Meta,
        value: Box<Expression>,
        dimension: Box<Expression>,
    },
}

#[derive(Clone)]
pub enum Access {
    ComponentAccess(String),
    ArrayAccess(Expression),
}
pub fn build_component_access(acc: String) -> Access {
    Access::ComponentAccess(acc)
}
pub fn build_array_access(expr: Expression) -> Access {
    Access::ArrayAccess(expr)
}

#[derive(Copy, Clone, Eq, PartialEq)]
pub enum AssignOp {
    AssignVar,
    AssignSignal,
    AssignConstraintSignal,
}

#[derive(Copy, Clone, PartialEq)]
pub enum ExpressionInfixOpcode {
    Mul,
    Div,
    Add,
    Sub,
    Pow,
    IntDiv,
    Mod,
    ShiftL,
    ShiftR,
    LesserEq,
    GreaterEq,
    Lesser,
    Greater,
    Eq,
    NotEq,
    BoolOr,
    BoolAnd,
    BitOr,
    BitAnd,
    BitXor,
}

#[derive(Copy, Clone, PartialEq)]
pub enum ExpressionPrefixOpcode {
    Sub,
    BoolNot,
    Complement,
}

// Knowledge buckets

#[derive(Copy, Clone, PartialOrd, PartialEq, Ord, Eq)]
pub enum TypeReduction {
    Variable,
    Component,
    Signal,
    Tag,
}

#[derive(Clone)]
pub enum LogArgument {
    LogStr(String),
    LogExp(Expression),
}
pub fn build_log_string(acc: String) -> LogArgument {
    LogArgument::LogStr(acc)
}
pub fn build_log_expression(expr: Expression) -> LogArgument {
    LogArgument::LogExp(expr)
}


#[derive(Default, Clone)]
pub struct TypeKnowledge {
    reduces_to: Option<TypeReduction>,
}
impl TypeKnowledge {
    pub fn new() -> TypeKnowledge {
        TypeKnowledge::default()
    }
    pub fn set_reduces_to(&mut self, reduces_to: TypeReduction) {
        self.reduces_to = Option::Some(reduces_to);
    }
    pub fn get_reduces_to(&self) -> TypeReduction {
        if let Option::Some(t) = &self.reduces_to {
            *t
        } else {
            panic!("reduces_to knowledge is been look at without being initialized");
        }
    }
    pub fn is_var(&self) -> bool {
        self.get_reduces_to() == TypeReduction::Variable
    }
    pub fn is_component(&self) -> bool {
        self.get_reduces_to() == TypeReduction::Component
    }
    pub fn is_signal(&self) -> bool {
        self.get_reduces_to() == TypeReduction::Signal
    }
    pub fn is_tag(&self) -> bool {
        self.get_reduces_to() == TypeReduction::Tag
    }
}

#[derive(Default, Clone)]
pub struct MemoryKnowledge {
    concrete_dimensions: Option<Vec<usize>>,
    full_length: Option<usize>,
    abstract_memory_address: Option<usize>,
}
impl MemoryKnowledge {
    pub fn new() -> MemoryKnowledge {
        MemoryKnowledge::default()
    }
    pub fn set_concrete_dimensions(&mut self, value: Vec<usize>) {
        self.full_length = Option::Some(value.iter().fold(1, |p, v| p * (*v)));
        self.concrete_dimensions = Option::Some(value);
    }
    pub fn set_abstract_memory_address(&mut self, value: usize) {
        self.abstract_memory_address = Option::Some(value);
    }
    pub fn get_concrete_dimensions(&self) -> &[usize] {
        if let Option::Some(v) = &self.concrete_dimensions {
            v
        } else {
            panic!("concrete dimensions was look at without being initialized");
        }
    }
    pub fn get_full_length(&self) -> usize {
        if let Option::Some(v) = &self.full_length {
            *v
        } else {
            panic!("full dimension was look at without being initialized");
        }
    }
    pub fn get_abstract_memory_address(&self) -> usize {
        if let Option::Some(v) = &self.abstract_memory_address {
            *v
        } else {
            panic!("abstract memory address was look at without being initialized");
        }
    }
}

 pub fn produce_report(error_code: ReportCode, location : FileLocation, file_id : FileID) -> Report {
    use ReportCode::*;
    let report  = match error_code {
            UnclosedComment => {
                let mut report =
                    Report::error("unterminated /* */".to_string(), ReportCode::UnclosedComment);
                report.add_primary(location, file_id, "Comment starts here".to_string());
                report
            }
            NoMainFoundInProject => Report::error(
                "No main specified in the project structure".to_string(),
                ReportCode::NoMainFoundInProject,
            ),
            MultipleMain =>{
                Report::error(
                    "Multiple main components in the project structure".to_string(),
                    ReportCode::MultipleMain,
                )
            }
            MissingSemicolon => {
                let mut report = Report::error(format!("Missing semicolon"), 
                    ReportCode::MissingSemicolon);
                report.add_primary(location, file_id, "A semicolon is needed here".to_string());
                report
            }
            UnrecognizedInclude => {
                let mut report =
                Report::error("unrecognized argument in include directive".to_string(), ReportCode::UnrecognizedInclude);
            report.add_primary(location, file_id, "this argument".to_string());
            report

            }
            UnrecognizedPragma => {
                let mut report =
                Report::error("unrecognized argument in pragma directive".to_string(), ReportCode::UnrecognizedPragma);
            report.add_primary(location, file_id, "this argument".to_string());
            report

            }        
            UnrecognizedVersion => {
                let mut report =
                Report::error("unrecognized version argument in pragma directive".to_string(), ReportCode::UnrecognizedVersion);
            report.add_primary(location, file_id, "this argument".to_string());
            report
            }      
            IllegalExpression => {
                let mut report =
                Report::error("illegal expression".to_string(), ReportCode::IllegalExpression);
            report.add_primary(location, file_id, "here".to_string());
            report
            }
            MultiplePragma => {
                let mut report =
                Report::error("Multiple pragma directives".to_string(), ReportCode::MultiplePragma);
            report.add_primary(location, file_id, "here".to_string());
            report
            },
            ExpectedIdentifier => {
                let mut report =
                Report::error("An identifier is expected".to_string(), ReportCode::ExpectedIdentifier);
            report.add_primary(location, file_id, "This should be an identifier".to_string());
            report
            },
            _ => unreachable!(),    
    };
    report
}

pub fn produce_version_warning_report(path : String, version : Version) -> Report {
    let mut r = Report::warning(
        format!(
            "File {} does not include pragma version. Assuming pragma version {:?}",
            path, version
        ),
        ReportCode::NoCompilerVersionWarning,
    );
    r.add_note(format!("At the beginning of file {}, you should add the directive \"pragma circom <Version>\", to indicate which compiler version you are using.",path));
    r
}


pub fn produce_report_with_message(error_code : ReportCode, msg : String) -> Report {
    match error_code {
        ReportCode::FileOs => {
            Report::error(
            format!("Could not open file {}", msg),
            ReportCode::FileOs,
            )
        }
        ReportCode::IncludeNotFound => {
            let mut r = Report::error(
                format!(" The file {} to be included has not been found", msg),
                ReportCode::IncludeNotFound,
                );
                r.add_note("Consider using compilation option -l to indicate include paths".to_string());
                r
        },
        _ => unreachable!()
    }
}

pub fn produce_compiler_version_report(path : String, required_version : Version, version :  Version) -> Report {
    let report = Report::error(
        format!("File {} requires pragma version {:?} that is not supported by the compiler (version {:?})", path, required_version, version ),
        ReportCode::CompilerVersionError,
    );
    report
}

pub fn anonymous_inside_condition_error(meta : Meta) -> Report {
    let msg = "An anonymous component cannot be used inside a condition ".to_string();
                let mut report = Report::error(
                    format!("{}", msg),
                    ReportCode::AnonymousCompError,
                );
                let file_id = meta.get_file_id().clone();
                report.add_primary(
                    meta.location,
                    file_id,
                    "This is an anonymous component used inside a condition".to_string(),
                );
                report
}

pub fn anonymous_general_error(meta : Meta, msg : String) -> Report {
    let mut report = Report::error(
                    format!("{}", msg),
                    ReportCode::AnonymousCompError,
                );
                let file_id = meta.get_file_id().clone();
                report.add_primary(
                    meta.location,
                    file_id,
                    "This is the anonymous component whose use is not allowed".to_string(),
                );
                report
}

pub fn tuple_general_error(meta : Meta, msg : String) -> Report {
    let mut report = Report::error(
                    format!("{}", msg),
                    ReportCode::TupleError,
                );
                let file_id = meta.get_file_id().clone();
                report.add_primary(
                    meta.location,
                    file_id,
                    "This is the tuple whose use is not allowed".to_string(),
                );
                report
}