typst / typst

A new markup-based typesetting system that is powerful and easy to learn.
https://typst.app
Apache License 2.0
31.56k stars 854 forks source link

distinguishing dicts from arrays is too subtle #4351

Closed DrGo closed 1 week ago

DrGo commented 1 month ago

Description

Currently, the following passes an array of dicts as an argument:

authors: (
(name:"So and So", affiliation:"University of That Place",),
),

but omitting the last comma passes a dict which causes code that expect an array to fail with messages like error: type dictionary has no method map

For most users, this can be a difficult to debug typo. For programmers used to other languages, this is a surprising behaviour.

I think this is an easily avoidable pain point ideally by unifying arrays and dicts (as e.g., Lua does) or by using distinct constructors e.g., { for dicts and ( for arrays or by treating the above example as an array of dicts (to be considered a dict, a field name must be specified:

authors: (
main_author: (name:"So and So", affiliation:"University of That Place",),
),

Reproduction URL

No response

Operating system

macOS

Typst version

laurmaedje commented 1 month ago

The error isn't really because dicts and arrays have similar syntax. It's because parenthesized expressions are close to single element arrays.

DrGo commented 1 month ago

I see, so there is no way to tell whether someone is adding arbitrary outer parens or constructing an array?

laurmaedje commented 1 month ago

The way to tell is the trailing comma.

DrGo commented 2 weeks ago

wondering if adding an (optional) constructor could help the compiler distinguish between the two and generate better messages for end users.

e.g.,

authors: vec(
(name:"So and So", affiliation:"University of That Place"),
)

this will be treated as a vector no matter what.

laurmaedje commented 1 week ago

I think this would lead to a style split and make it harder to learn the normal array syntax. It's a bit unfortunate that we can't use [..] syntax for arrays (because content), but that's a trade-off that was necessary. Moreover, various other languages that do use [..] still have the trailing comma parentheses syntax for tuples (Python and Rust come to mind), so we're in good company.