Commit graph

152 commits

Author SHA1 Message Date
martin
3b5329aa20
feat: add support for PEP758 (#1401)
Some checks are pending
CI / test (macos-latest, 3.13) (push) Waiting to run
CI / test (macos-latest, 3.13t) (push) Waiting to run
CI / test (macos-latest, 3.14) (push) Waiting to run
CI / test (macos-latest, 3.14t) (push) Waiting to run
CI / test (macos-latest, 3.9) (push) Waiting to run
CI / test (ubuntu-latest, 3.10) (push) Waiting to run
CI / test (ubuntu-latest, 3.11) (push) Waiting to run
CI / test (ubuntu-latest, 3.12) (push) Waiting to run
CI / test (ubuntu-latest, 3.13) (push) Waiting to run
CI / test (ubuntu-latest, 3.13t) (push) Waiting to run
CI / test (ubuntu-latest, 3.14) (push) Waiting to run
CI / test (ubuntu-latest, 3.14t) (push) Waiting to run
CI / test (ubuntu-latest, 3.9) (push) Waiting to run
CI / test (windows-latest, 3.10) (push) Waiting to run
CI / test (windows-latest, 3.11) (push) Waiting to run
CI / test (windows-latest, 3.12) (push) Waiting to run
CI / test (windows-latest, 3.13) (push) Waiting to run
CI / test (windows-latest, 3.13t) (push) Waiting to run
CI / test (windows-latest, 3.14) (push) Waiting to run
CI / test (windows-latest, 3.14t) (push) Waiting to run
CI / test (windows-latest, 3.9) (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
CI / docs (push) Waiting to run
CI / Rust unit tests (push) Waiting to run
CI / Rustfmt (push) Waiting to run
CI / build (push) Waiting to run
pypi_upload / build (push) Waiting to run
pypi_upload / Upload wheels to pypi (push) Blocked by required conditions
GitHub Actions Security Analysis with zizmor 🌈 / zizmor latest via PyPI (push) Waiting to run
PEP758 removes the requirement for parentheses to surround exceptions
in except and except* expressions when 'as' is not present.

This pr implements support for parsing these types of statements
2025-09-09 11:16:49 -04:00
martin
48668dfabb
Support parsing of t-strings #1374 (#1398)
#1343
Adds support to parse t-strings

Couple things of note:

TemplatedString* is largely a copy of FormattedString*
Since clients operate of libcst objects I consider this this part of a public API - following the python grammar (where TStrings are distinct from FStrings) seems like a good way to avoid changes to the API in the future.
Within the tokenizer we reuse the fstring machinery
I consider this an implementation detail, fstrings and tstrings are (for now) identical, we can change this later without changes to the public api.
Since 2 -> we have a new FTStringType enum
We need to discriminate between f and t strings to know which token to return, a bit clumsy to use in my opinion - so looking for feedback here on how to improve this.
2025-09-09 11:16:20 -04:00
Ken Kawamoto
7090a0db2b
fixes match statements to work with PositionProvider (#1389)
* add failing test

* fix issue

* fixes an issue with PositionProvider not working with case statement

* remove comments

---------

Co-authored-by: steve <steve@patreon.com>
2025-08-04 17:27:13 -04:00
martin
9542fc3882
remove entry points to pure parser (#1375)
* rm: ci

* rm: entry point

* fix: tests

* fix: remove combine step from ci

* linter fixes

* omit the _parser

* fix newlines

* fix: remove optional

* fix: linter

---------

Co-authored-by: thereversiblewheel <martin.li@uwaterloo.ca>
2025-07-30 16:27:20 +00:00
zaicruvoir1rominet
ca1f81f049
Avoid raising bare Exception (#1168)
* Keep old exception messages (avoid breaking-changes for users relying on exception messages)

* Move ``get_expected_str`` out of _exceptions.py, where it does not belong, to its own file in _parser/_parsing_check.py
2025-06-07 01:53:44 -07:00
dependabot[bot]
bf5fb4132e
Bump black from 23.12.1 to 24.8.0 (#1186)
* Bump black from 23.12.1 to 24.8.0

Bumps [black](https://github.com/psf/black) from 23.12.1 to 24.8.0.
- [Release notes](https://github.com/psf/black/releases)
- [Changelog](https://github.com/psf/black/blob/main/CHANGES.md)
- [Commits](https://github.com/psf/black/compare/23.12.1...24.8.0)

---
updated-dependencies:
- dependency-name: black
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* Update formatting

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Amethyst Reese <amethyst@n7.gg>
2024-08-22 16:46:01 -07:00
Kirill Ignatev
b0d145dddd
Add validation for If node (#1177)
* Add validation for If node

Don't allow no space no parentheses.
2024-07-30 09:01:07 +01:00
Zsolt Dollenstein
8b97600fb3
fix various Match statement visitation errors (#1161)
Fixes #1160.

This PR also

- fixes `whitespace_before_colon` being swallowed during visitation on `MatchCase`s
- adds a new type of roundtrip test that catches issues of this class: the test applies a noop transformer to exercise the visitation API and compares the result with the original source.
- adds a few more cases to the match fixture
2024-06-12 17:29:25 +01:00
martin
71b0a1288b
Implement Type Defaults for Type Parameters (PEP 696) (#1141)
Co-authored-by: thereversiblewheel <martin.li@uwaterloo.ca>
2024-05-20 11:26:38 -04:00
Zsolt Dollenstein
2ffca10845
remove typing dependencies (#1126)
Summary:
This PR removes the `typing_extensions` and `typing_inspect` dependencies as we can now rely on the built-in `typing` module since Python 3.9.

Test Plan:
existing tests
2024-04-03 19:50:14 +01:00
Zsolt Dollenstein
c854c986b6
Fix parsing list matchers without explicit brackets (#1097)
```
match a:
  case 1, 2: pass
```

This is parsed correctly by the grammar, but the default values of `MatchList.lbracket` and `MatchList.rbracket` are inconsistent between Python and Rust, causing the above snippet to round-trip (from Python) to:
```
match a:
  case [1, 2]: pass
```

Fixes #1096.
2024-02-02 20:49:25 +00:00
Zsolt Dollenstein
738dc2f893
Upgrade pyre (#1032)
* Upgrade pyre

* regen fixtures
2023-10-02 09:43:17 -07:00
Zsolt Dollenstein
9286446f88
PEP 695 - Type Parameter Syntax (#1004)
This PR adds support for parsing and representing Type Parameters and Type Aliases as specified by PEP 695. What's missing are the scope rules, to be implemented in a future PR.

Notable (user visible) changes:

- new `TypeAlias` CST node, which is a `SmallStatement`
- new CST nodes to represent TypeVarLikes: `TypeVar`, `TypeVarTuple`, `ParamSpec`
- new helper CST nodes:  `TypeParameters` to serve as a container for multiple TypeVarLikes, and `TypeParam` which is a single item in a `TypeParameters` (owning the separating comma)
- extended `FunctionDef` and `ClassDef` with an optional `type_parameters` field, as well as `whitespace_after_type_parameters` to own the extra whitespace between type parameters and the following token
  - these new fields are added after all others to avoid breaking callers passing in fields as positional arguments
- in `FunctionDef` and `ClassDef`, `whitespace_after_name` now owns the whitespace before the type parameters if they exist
2023-08-28 22:07:22 +01:00
Zsolt Dollenstein
2acc293347
Fix whitespace, fstring, walrus related parse errors (#939, #938, #937, #936, #935, #934, #933, #932, #931)
* Allow walrus in slices

See https://github.com/python/cpython/pull/23317

Raised in #930.

* Fix parsing of nested f-string specifiers

For an expression like `f"{one:{two:}{three}}"`, `three` is not in an f-string spec, and should be tokenized accordingly.

This PR fixes the `format_spec_count` bookkeeping in the tokenizer, so it properly decrements it when a closing `}` is encountered but only if the `}` closes a format_spec.

Reported in #930.

* Fix tokenizing `0else`

This is an obscure one.

`_ if 0else _` failed to parse with some very weird errors. It turns out that the tokenizer tries to parse `0else` as a single number, but when it encounters `l` it realizes it can't be a single number and it backtracks.

Unfortunately the backtracking logic was broken, and it failed to correctly backtrack one of the offsets used for whitespace parsing (the byte offset since the start of the line). This caused whitespace nodes to refer to incorrect parts of the input text, eventually resulting in the above behavior.

This PR fixes the bookkeeping when the tokenizer backtracks.

Reported in #930.

* Allow no whitespace between lambda keyword and params in certain cases

Python accepts code where `lambda` follows a `*`, so this PR relaxes validation rules for Lambdas.

Raised in #930.

* Allow any expression in comprehensions' evaluated expression


This PR relaxes the accepted types for the `elt` field in `ListComp`, `SetComp`, and `GenExp`, as well as the `key` and `value` fields in `DictComp`.

Fixes #500.

* Allow no space around an ifexp in certain cases

For example in `_ if _ else""if _ else _`.

Raised in #930. Also fixes #854.

* Allow no spaces after `as` in a contextmanager in certain cases

Like in `with foo()as():pass`

Raised in #930.

* Allow no spaces around walrus in certain cases

Like in `[_:=''for _ in _]`

Raised in #930.

* Allow no whitespace after lambda body in certain cases

Like in `[lambda:()for _ in _]`

Reported in #930.
2023-06-07 12:37:16 +01:00
Sergii Dymchenko
062bcdb07e
Fix Sentinal typo (#948) 2023-06-07 12:23:12 +01:00
Sigurd Ljødal
a594fe1dd2
Fix type of evaluated_value on string to allow bytes (#721)
* Fix type of evaluated_value on string

This can return bytes if the string is a bytestring, e.g.:

    In [1]: import libcst as cst

    In [2]: cst.parse_expression('b"foo"').evaluated_value
    Out[2]: b'foo'

* Fix type errors from changed signature
2023-05-26 13:43:05 +01:00
John Litborn
38b708b5ed
relax validation rules on decorators (#926)
* relax validation on decorators

* allow any expression

---------

Co-authored-by: Zsolt Dollenstein <zsol.zsol@gmail.com>
2023-05-23 09:56:49 +01:00
Rebecca Chen
f936db240f
Fix ApplyTypeAnnotationsVisitor behavior on attribute assignments. (#903)
* Fixes an issue where ApplyTypeAnnotationsVisitor would crash on code
  like `SomeClass.some_attribute = 42` with a "Name is not a valid
  identifier" error message.
* Changes the above-mentioned error message to include the bad name in
  the message, for easier debugging.
* Adds tests for all valid assignment targets, as described here:
  https://libcst.readthedocs.io/en/latest/nodes.html#libcst.BaseAssignTargetExpression.
2023-04-05 14:23:53 -07:00
dependabot[bot]
46509dd5e1
Bump black from 22.12.0 to 23.1.0 (#860) 2023-03-15 11:53:50 +00:00
Zsolt Dollenstein
343f56f607
[parser] bail on deeply nested expressions (#718) 2022-07-04 14:45:42 +01:00
Zsolt Dollenstein
9925117391
Support whitespace after ParamSlash (#713)
* add whitespace_after field to ParamSlash
* codegen
2022-06-26 09:42:37 +01:00
zzl
7ca1bd1cd5
expression: fix SimpleString's quote method (#704)
* expression: fix SimpleString's quote method

* Add missing copyright header

Co-authored-by: zzl0 <zhuzhaolong0@mail.com>
Co-authored-by: Luke Petre <lpetre@fb.com>
2022-06-17 13:05:05 +01:00
Zsolt Dollenstein
ebe1851c2b
Add support for PEP-646 (#696) 2022-06-13 09:52:31 -06:00
Zsolt Dollenstein
3af6820ca7
Fix space validation for AsName and Await (#641)
* Fix space validation for AsName and Await

* Update libcst/_nodes/tests/test_import.py

Co-authored-by: Steven Troxler <steven.troxler@gmail.com>
2022-02-10 10:21:54 -08:00
Zsolt Dollenstein
c91655fbba
fix copyright headers and add a script to check (#635) 2022-02-01 11:13:17 +00:00
Batuhan Taskaya
5b6b19af84
Proxy both parentheses in some pattern matching nodes (#626) 2022-01-25 11:02:08 +00:00
Batuhan Taskaya
68780fd6b2
Don't require whitespace right after match (#628) 2022-01-24 09:20:44 -08:00
Batuhan Taskaya
2345848d4a
[native] Allow unparenthesized tuples inside f-strings (#621) 2022-01-23 09:10:47 -08:00
Batuhan Taskaya
2b2b25bb08
Don't redundantly nest StarredElement inside another Element (#624) 2022-01-23 05:45:27 -08:00
Arie Bovenberg
bd5ede7953
add slots to base classes, @add_slots takes bases into account (#605)
* add slots to base classes, @add_slots takes bases into account
* state changes in apache 2.0 licensed add_slots
2022-01-16 14:14:32 +00:00
Steven Troxler
1337022770
[WIP] Support Parenthesized With Statements (#584)
On the python side, we can add parentheses from MaybeSentinel.DEFAULT if the whitespace requires it.

On the rust side, we support the new grammar but codegen will only add explicitly included parentheses for now - it should be possible to match python behavior but it's not urgent so I've left a TODO
2022-01-07 12:21:58 -08:00
Steven Troxler
3578f2fc3d
Add some color to children-vs-codegen error (#583)
It took me some time to track down the root cause of `children`
not matching codegen, having the error message directly hint that
visit and codegen are probably mimatched (my visit was running
out-of-order) will likely help newbies get going faster.
2022-01-05 21:26:51 +00:00
Zsolt Dollenstein
d9a1dc8473
Fix all type errors (#579)
* bump pyre version
* make sure CI-pyre uses working copy
* remove unused pyre suppressions
* suppress invalid decorations
* fix undefined attributes
* fix missing return annotations
* fix tuple concatenation issues
* add native stubs
* fix invalid typing of **kwargs in test_apply_type_annotations
* only install pyre on non-windows
* update test fixture to reflect changes in recent pyre versions
* suppress errors related to mismatched positions
2022-01-05 18:13:01 +00:00
Zsolt Dollenstein
9932a6d339
Implement PEP-634 - Match statement (#568)
* ParenthesizedNode implementation for Box

* match statement rust CST and grammar

* match statement python CST and docs

* run rust unit tests in release mode for now
2021-12-30 10:00:51 +00:00
Zsolt Dollenstein
67db03915d
implement PEP-654: except* (#571) 2021-12-29 21:23:46 +00:00
Zsolt Dollenstein
c44ff0500b
Fix license headers (#560)
* Facebook -> Meta

* remove year from doc copyright
2021-12-28 11:55:18 +00:00
John Reese
10c3aa09a7
Upgrade to µsort 1.0.0rc1, and apply formatting changes (#565)
* Upgrade to usort==1.0.0rc1

* Apply sorting changes from usort 1.0.0rc1

* reapply codegen

Co-authored-by: Zsolt Dollenstein <zsol.zsol@gmail.com>
2021-12-21 14:55:04 -08:00
Zsolt Dollenstein
c02de9b718
Implement a Python PEG parser in Rust (#566)
This massive PR implements an alternative Python parser that will allow LibCST to parse Python 3.10's new grammar features. The parser is implemented in Rust, but it's turned off by default through the `LIBCST_PARSER_TYPE` environment variable. Set it to `native` to enable. The PR also enables new CI steps that test just the Rust parser, as well as steps that produce binary wheels for a variety of CPython versions and platforms.

Note: this PR aims to be roughly feature-equivalent to the main branch, so it doesn't include new 3.10 syntax features. That will be addressed as a follow-up PR.

The new parser is implemented in the `native/` directory, and is organized into two rust crates: `libcst_derive` contains some macros to facilitate various features of CST nodes, and `libcst` contains the `parser` itself (including the Python grammar), a `tokenizer` implementation by @bgw, and a very basic representation of CST `nodes`. Parsing is done by
1. **tokenizing** the input utf-8 string (bytes are not supported at the Rust layer, they are converted to utf-8 strings by the python wrapper)
2. running the **PEG parser** on the tokenized input, which also captures certain anchor tokens in the resulting syntax tree
3. using the anchor tokens to **inflate** the syntax tree into a proper CST

Co-authored-by: Benjamin Woodruff <github@benjam.info>
2021-12-21 18:14:39 +00:00
Steven Troxler
5e1e3fe970
The ufmt tool combines usort and black with a consistent wrapper, (#515)
which ensures we won't have inconsistent black-vs-isort errors
going forward. We can always format by running `ufmt format .`
at the root, and check with `ufmt check .` in our CI actions.
2021-08-25 20:39:29 -04:00
Tim Hatch
9a6fd56653
Improve handling of raw fstrings (#462) (#466) 2021-03-29 09:08:05 +01:00
Caleb Donovick
0ee0831eb6
Add FlattenSentinel to support replacing a statement with multiple statements (#455)
* Add flatten_sentinal

* Add FlattenSentinal to __all__

* Fix lint errors

* Fix type errors

* Update test to use leave_Return

* Update and run codegen

* Add empty test

* Update docs

* autofix
2021-03-22 23:23:40 -07:00
Tim Hatch
02fc4401bc
Support Named Unicode Characters and yield in f-strings (#424)
* Support named unicode characters in f-strings

This is the same as my pull request
https://github.com/davidhalter/parso/pull/160

* A small bugfix to what is allowed in f-string expressions

Thanks to https://github.com/davidhalter/parso/pull/159 for catching
that yield (as an expression, I suppose) is allowed on 3.6.
2020-11-30 12:42:13 +08:00
Tim Hatch
90df5a6a37
Allow generator expressions in f-strings (#419)
Fixes #388
2020-11-17 17:32:43 +00:00
Tim Hatch
31bae01ccb
Correct handling of walrus operator in function args (#417)
Previous behavior treated it as identical to equal, making a kwarg; it should
instead be a positional arg.  Includes several tests to make sure that
whitespace handling is correct.

Fixes #416
2020-11-12 21:14:34 -08:00
Caleb Donovick
6731aa5d29
Use correct type for AugAssign and AnnAssign target (#396)
* Use correct type

* Add tests

* Suppress intentional type errors in pyre
2020-10-01 13:45:41 -07:00
Jimmy Lai
7ca738bf39
Upgrade dev tools (Black/Flake8/isort) and read install requirements from requirements.txt (#380)
* Read install requirements from requirements.txt

* read extras_require from requirements-dev.txt

* add requirements-dev.txt to MANIFEST.in

* apply fixes for new version of Black and Flake8

* don't upgrade Pyre

* re-format
2020-08-31 10:44:55 -07:00
Sebastian Kreft
b4e04eae63
fix: spaces around walrus operator are not required (#368)
Fixes #367
2020-08-12 14:55:11 +01:00
Germán Méndez Bravo
17bde3b3aa
Fix pyre syntax error in tokenizer stub (#360)
## Summary

The pyre stub for the tokenizer module had a syntax error.
Fixing it removes other pyre errors.

## Test Plan

```
pyre check
```

Co-authored-by: Germán Méndez Bravo <kronuz@fb.com>
2020-08-04 17:33:55 -07:00
Sebastian Kreft
a9177e27bc
fix: allow ParenthesizedWhitespace before params in FuncDef (#342)
* fix: allow ParenthesizedWhitespace before params in FuncDef

Fixes #303

* fix: run codegen
2020-07-15 12:59:38 -07:00
Sebastian Kreft
f36eacb132
fix: improve validation for ImportAlias and Try statements (#340)
* fix: improve validation for ImportAlias and Try statements

For `Try` statements we ensure that the bare except, if present, is at the last position.

For ImportAlias we ensure that the imported name is valid.

Fixes #287

* Apply suggestions from code review

Add missing periods.

* Apply suggestions from code review

Add missing periods.

* Update libcst/_nodes/tests/test_import.py

Co-authored-by: jimmylai <yurinai@gmail.com>
2020-07-13 19:32:33 -07:00