Skip to content

Commit e1d2ac2

Browse files
Raise an error when mutating method is accessed outside of a call expression
1 parent 674f7b4 commit e1d2ac2

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

crates/typst-eval/src/code.rs

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@ use ecow::{EcoVec, eco_vec};
22
use typst_library::diag::{At, SourceResult, bail, error, warning};
33
use typst_library::engine::Engine;
44
use typst_library::foundations::{
5-
Array, Capturer, Closure, Content, ContextElem, Dict, Func, NativeElement, Selector,
6-
Str, Value, ops,
5+
Array, Capturer, Closure, Content, ContextElem, Dict, Func, NativeElement, Repr,
6+
Selector, Str, Value, ops,
77
};
88
use typst_library::introspection::{Counter, State};
9+
use typst_syntax::Span;
910
use typst_syntax::ast::{self, AstNode};
1011
use typst_utils::singleton;
1112

13+
use crate::methods::is_mutating_method;
1214
use crate::{CapturesVisitor, Eval, FlowEvent, Vm};
1315

1416
impl Eval for ast::Code<'_> {
@@ -319,7 +321,10 @@ impl Eval for ast::FieldAccess<'_> {
319321
let field_span = field.span();
320322

321323
let err = match value.field(&field, (&mut vm.engine, field_span)).at(field_span) {
322-
Ok(value) => return Ok(value),
324+
Ok(field) => {
325+
validate_method_access(&value, &field, field_span)?;
326+
return Ok(field);
327+
}
323328
Err(err) => err,
324329
};
325330

@@ -389,3 +394,15 @@ fn warn_for_discarded_content(engine: &mut Engine, event: &FlowEvent, joined: &V
389394

390395
engine.sink.warn(warning);
391396
}
397+
398+
/// Raises an error if a user tries to access a mutating method outside of a call expression.
399+
fn validate_method_access(target: &Value, field: &Value, span: Span) -> SourceResult<()> {
400+
let Value::Func(f) = field else { return Ok(()) };
401+
let Some(name) = f.name() else { return Ok(()) };
402+
403+
if is_mutating_method(name) {
404+
bail!(span, "cannot access mutating fields on {}", target.repr());
405+
}
406+
407+
Ok(())
408+
}

tests/suite/scripting/field.typ

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,7 @@
7474
// Hint: 3-4 try creating a new stroke with the updated field value instead
7575
s.thickness = 5pt
7676
}
77+
78+
--- field-mutable-cannot-access ---
79+
// Error: 8-12 cannot access mutable fields on array
80+
#array.push

0 commit comments

Comments
 (0)