Commit Graph

993 Commits

Author SHA1 Message Date
Stefan Holderbach
e427c68731
Relax type-check of key-less table/record (#10629)
# Description
Relax typechecking of key-less `table`/`record`

Assume that they are acceptable for more narrowly specified
`table<...>`/`record<...>` where `...` specifies keys and potentially
types for those keys/columns.

This ensures that you can use commands that specify general return
values statically with more specific input-/args-type requirements.

Reduces the power of the type-check a bit but unlocks you to actually
use the specific annotations in more places.
Incompatibilities will only be raised if an output type declares
specific columns/keys.

Closes #9702

Supersedes #10594 as a simpler solution requiring no extra distinction.

h/t @1kinoti, @NotLebedev
# User-Facing Changes
Now legal at type-check time

```nu
def foo []: nothing -> table { [] }
def foo []: nothing -> table<> { ls }
def bar []: table<a:int,b:string> -> nothing {}

foo | bar 
```

# Tests + Formatting
- 1 explicit test with specified relaxed return type passed to concrete
expected input type
- 1 test leveraging the general output type of a built-in command
- 1 test wrapping a general built-in command and verifying the type
inference in the function body
2023-10-08 13:26:36 +02:00
Jakub Žádník
4efccb2b1c
Fix parsing of signature inp/out types in predecls (#10642)
# Description
Fixes https://github.com/nushell/nushell/issues/10605 (again).

The loop looking for `[` to determine signature position didn't stop
early enough, so it thought the second `[` denoting the inp/out types
marks the beginning of the signature.

# User-Facing Changes

# Tests + Formatting
adds a new `predecl_signature_multiple_inp_out_types` test

# After Submitting
2023-10-08 12:58:26 +02:00
Jakub Žádník
67b5e1bde9
Fix wrong parsing of signatures in predecl scan (#10637) 2023-10-07 16:42:09 +03:00
Stefan Holderbach
399319476a
Move SyntaxShape specifier parsing into own file (#10448)
Pure move refactor.

Followup to:
- #10511
- #10512
- #10544 
- #10548 
- #10581
2023-10-05 23:31:40 +02:00
Stefan Holderbach
4f4e8c984e
Parse custom completer annotation only in args (#10581)
# Description
To my knowledge `type@completer` annotations only make sense in
arguments at the moment.
Restrict the parsing.
Also fix a bug in parsing the completer annotation should there be more
than 1 `@`


- Add test that we disallow completer in type
- Guard against `@` inside command name
- Disallow custom completers in type specification


# User-Facing Changes
Error when annotating a variable or input-output type with a completer

# Tests + Formatting
Tests to verify the error message
2023-10-05 22:39:37 +02:00
Jakub Žádník
eb6870cab5
Add --env and --wrapped flags to def (#10566) 2023-10-02 21:13:31 +03:00
Stefan Holderbach
9e445fd4c5
Rename SyntaxShape::Custom to CompleterWrapper (#10548)
# Description
The description `Custom` doesn't really reflect meaning in the set of
`SyntaxShape`. Makes it a bit more verbose but explicit


# User-Facing Changes
Only hypothetically breaking as plugins can not effectively use a
requirement on `SyntaxShape::Custom`.

# Tests + Formatting
(-)
2023-09-29 19:22:58 +02:00
Stefan Holderbach
f2af12af2c
Docstring some intricacies around SyntaxShape (#10544)
Inspired by @fdncred and @amtoine's questions
https://github.com/nushell/nushell/pull/10512#issuecomment-1739996967
2023-09-29 16:35:22 +02:00
Stefan Holderbach
dc739f703a
Remove parsing literals of unrepresentable SyntaxShapes (#10512)
# Description
Those `SyntaxShape`s can not coerce to `Value`s or `Type`s that can be
used by the user in an argument or input-output-type position.
Supporting them doesn't make sense.

# User-Facing Changes
Removal of useless "types" in argument type or input/output type
positions

# Tests + Formatting
No adjustment necessary
2023-09-28 22:36:47 +02:00
Stefan Holderbach
d1dc610769
Remove unused SyntaxShape::Variable (#10511)
# Description
We don't use this shape during parsing and never reference it in command
signatures. Thus it should be removed.

# User-Facing Changes
None functional.
Plugin authors that used it would never be provided with data that
specifically matched `SyntaxShape::Variable`
Builds using it will now fail.

# Tests + Formatting
NA
2023-09-28 11:53:03 +02:00
Antoine Stevan
6c026242d4
remove the $nothing variable (#10478)
related to 
- https://github.com/nushell/nushell/pull/9973
- https://github.com/nushell/nushell/pull/9918

thanks to @jntrnr and their super useful tips on this PR, i learned
about the parser + evaluation, so 🙏

# Description
because we already have `null` as the value of the type `nothing` and as
a followup to the two other attempts of mine, i propose to remove the
redundant `$nothing` built-in variable 😋

this PR is the first step, deprecating `$nothing`.
a followup PR will remove it altogether and wait for 0.87 👍 

⚙️ **details**: a new `NOTHING_VARIABLE_ID = 3` has been added,
parsing `$nothing` will create it, finally a `Value::Nothing` will be
produced and a warning will be reported.

this PR already fixes the `toolkit.nu` module so that it does not throw
a bunch of warnings each time 👌

# User-Facing Changes
`$nothing` is now deprecated and will be removed in 0.87
```nushell
> $nothing
Error:   × Deprecated variable
   ╭─[entry #1:1:1]
 1 │ $nothing
   · ────┬───
   ·     ╰── `$nothing` is deprecated and will be removed in 0.87.
   ╰────
  help: Use `null` instead
```

# Tests + Formatting
tests have been updated, especially
- `nothing_fails_string`
- `nothing_fails_int`
which use a variable called `nil` now to make sure `nothing` does not
support cell paths 👍

# After Submitting
classic deprecation mention 👍
2023-09-26 18:49:28 +02:00
Artemiy
e96039fb1b
Fix default argument value type checking (#10460)
# Description
Fix type checking in arguments default values not adhering to subtyping
rules
Currently following examples produce a parse error:
```nu
def test [ --qwe: record<a: int> = {a: 1 b: 1} ] { }
def test [ --qwe: list<any> = [ 1 2 3 ] ] { }
```
despite types matching. Type equality check is replaced with subtyping
check and everything parses fine:
# User-Facing Changes
Default values of flag arguments type checking behavior is in line with
`let` statements
2023-09-24 11:30:58 +02:00
Artemiy
65e2733571
Allow complex types in input/output and let (#10405)
# Description
This PR fixes #9702 on the side of parse. I.e. input/output types in
signature and type annotations in `let` now should correctly parse with
type annotations that contain commas and spaces:

![image](https://github.com/nushell/nushell/assets/17511668/babc0a69-5cb3-46c2-98ef-6da69ee3d3be)

# User-Facing Changes
Return values and let type annotations now can contain stuff like
`table<a: int b: record<c: string d: datetime>>` e.t.c
2023-09-24 11:01:21 +02:00
Antoine Stevan
6a2fd91a01
show the whole path in "missing mod.nu" errors (#10416) 2023-09-23 16:30:03 +03:00
WindSoilder
d2c87ad4b4
differentiating between --x and --x: bool (#10456)
# Description
Fixes: #10450 

This pr differentiating between `--x: bool` and `--x`

Here are examples which demostrate difference between them:
```nushell
def a [--x: bool] { $x };
a --x    # not allowed, you need to parse a value to the flag.
a        # it's allowed, and the value of `$x` is false, which behaves the same to `def a [--x] { $x }; a`
```

For boolean flag with default value, it works a little bit different to
#10450 mentioned:
```nushell
def foo [--option: bool = false] { $option }
foo                  # output false
foo --option         # not allowed, you need to parse a value to the flag.
foo --option true    # output true
```

# User-Facing Changes
After the pr, the following code is not allowed:
```nushell
def a [--x: bool] { $x }; a --x
```

Instead, you have to pass a value to flag `--x` like `a --x false`. But
bare flag works in the same way as before.

## Update: one more breaking change to help on #7260 
```
def foo [--option: bool] { $option == null }
foo
```
After the pr, if we don't use a boolean flag, the value will be `null`
instead of `true`. Because here `--option: bool` is treated as a flag
rather than a switch

---------

Co-authored-by: amtoine <stevan.antoine@gmail.com>
2023-09-23 10:20:48 +02:00
Andreas Källberg
6df001f72d
Prevent cubic time on nested parentheses (#10467)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

When parse_range get an item like ((((1..2)))) it would try to parse
"((((1" with a long chain of recursive parsers, namely:
- parse_value
- parse_paren_expr
- parse_full_cell_path
- parse_block
- parse_pipeline
- parse_builtin_commands
- parse_expression
- parse_math_expression
- parse_value
- ...

where `parse_paren_expr` calls `parse_range` in turn. Because at any
time in the chain `parse_paren_expr` can call `parse_range`, which will
then continue the chain, we get quadratic number of function calls, each
linear on the size of the input

By checking with the lexer that the parens are matched, we prevent the
long chain from being called on unmatched braces. Now, this is still
more quadratic than it needs to be, to fix that, we should process
parens only once, instead of on each recursive call

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
Speed improvements in some edge cases

# Tests + Formatting
Not sure how to test this, maybe I could add a benchmark
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->

# Other notes
Found using the fuzzer, by setting a timeout on max run-time. It also
found a stack-overflow on too many parentheses, which this doesn't fix.
2023-09-23 04:24:35 +12:00
WindSoilder
bf40f035f6
don't overrite arg's type if it's annotated explicitly (#10424)
# Description
Fixes: #10410 

So the following script is possible:
```nushell
def a [b: any = null] { let b = ($b | default "default_b"); }
a "given_b"
```

## About the change
When parsing signature, and nushell meets something like `a: any`, it
force the parser to treat `a` as `any` type. This is what
`arg_explicit_type` means, it's only set when we goes into
`ParseMode::TypeMode`, and it will be reset to `false` if the token goes
to next argument.

so, when we have something like this: `def a [b: any = null] { $b }`,
the type of `$b` won't be overwritten.

But if we have something like this: `def a [b = null] { $b }`, the type
of `$b` is not annotated, so we make it to be `nothing`(which is the
type of null)
2023-09-21 03:58:29 +12:00
Andreas Källberg
8d8b44342b
Fix exponential parser time on sequence of [[[[ (#10439)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

Before this change, parsing `[[[[[[[[[[[[[[[[[[[[[[` would cause nushell
to consume several gigabytes of memory, now it should be linear in time.

The old code first tried parsing the head of the table as a list and
then after that it checked if it got more arguments. If it didn't, it
throws away the previous result and tries to parse the whole thing as a
list, which means we call `parse_list_expression` twice for each call to
`parse_table_expression`, resulting in the exponential growth

The fix is to simply check that we have all the arguments we need before
parsing the head of the table, so we know that we will either call
parse_list_expression only on sub-expressions or on the whole thing,
never both.

Fixes #10438


# User-Facing Changes
Should give a noticable speedup when typing a sequence of `[[[[[[` open
brackets
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting

I would like to add tests, but I'm not sure how to do that without
crashing CI with OOM on regression

- [x] Don't forget to add tests that cover your changes.
- [x] `cargo fmt --all -- --check` to check standard code formatting
(`cargo fmt --all` applies these changes)
- [x] `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used`
to check that you're using the standard code style
- [x] `cargo test --workspace` to check that all tests pass (on Windows
make sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- [x] `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library
<!--
> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
2023-09-21 03:53:48 +12:00
Stefan Holderbach
af15f794b4
Bump to 0.85.1 development version (#10431) 2023-09-20 18:38:42 +12:00
Stefan Holderbach
a6f62e05ae
Bump version for the 0.85 release (#10425) 2023-09-19 21:42:47 +03:00
Dongjia "toka" Zhang
bc7736bc99
Add 2 fuzzers for nu-path, nu-parser (#10376)
# Description

This PR adds a fuzzer for the nu-path and the nu-parser crate.
Now you can go to `crates/nu-path/fuzz`/`crates/nu-parser/fuzz` and run `cargo fuzz` to
find crashes.
https://github.com/nushell/nushell/issues/10365 and #9417 was found by
this


---------

Co-authored-by: sholderbach <sholderbach@users.noreply.github.com>
2023-09-16 22:32:53 +02:00
Stefan Holderbach
bbf0b45c59
Update internal use of decimal to float (#10333)
# Description
We made the decision that our floating point type should be referred to
as `float` over `decimal`.
Commands were updated by #9979 and #10320

Now make the internal codebase consistent in referring to this data type
as `float`.

Work for #10332

# User-Facing Changes

`decimal` has been removed as a type name/symbol. 

Instead of 
```nushell
def foo [bar: decimal] decimal -> decimal {}
```
use 
```nushell
def foo [bar: float] float -> float {}
```

Potential effect of `SyntaxShape`'s `Display` implementation now also
referring to `float` instead of `decimal`

# Details
- Rename `SyntaxShape::Decimal` to `Float`
- Update `Display for SyntaxShape` to `float`
- Update error message + fn name in dataframe code
- Fix docs in command examples
- Rename tests that are float specific
- Update doccomment on `SyntaxShape`
- Update comment in script

# Tests + Formatting
Updates the names of some tests
2023-09-13 23:53:55 +02:00
Stefan Holderbach
7f39609d9a
Remove python-like string multiplication (#10293)
# Description
Currently we support "multiplication" of strings, resulting in a terse
way to repeat a particular string.
This can have unintended side effects when dealing with mixed data (e.g.
after parsing data that is not all numbers).
Furthermore as we frequently fall-back to strings while parsing source
code, this introduced a runaway edge case in const evaluation (#10212)

Work for #10233

## Details
- Remove python-like string multiplication.
- Workaround for indentation
  - This should probably be addressed with a purpose built command
- Remove special const-eval error test

# User-Facing Changes
**Major breaking change!**
`"string" * 42` will stop working. (This was used for example in the
stdlib)

We should bless a good alternative before landing this

---------

Co-authored-by: JT <547158+jntrnr@users.noreply.github.com>
2023-09-13 19:52:04 +12:00
Stefan Holderbach
a14e9e0a2e
Invert &Options to Option<&T> (#10315)
Elide the reference for `Copy` type (`usize`)
Use the canonical deref where possible.
* `&Box` -> `&`
* `&String` -> `&str`
* `&PathBuf` -> `&Path`

Skips the ctrl-C handler for now.
2023-09-13 07:00:58 +08:00
Stefan Holderbach
3e14dc3eb8
Remove pythonic int * list behavior (#10292)
# Description
The pythonism that multiplying a scalar integer with a list results in a
repeated concatenation of the list, is ambiguous with other possible
interpretations and thus actively harmful to clear semantics in nushell.

Another possible reading of this scalar/vector product would be trying
to perform elementwise multiplication with the scalar.

Before we bless this alternative as a more reasonable design the best
course of action is to remove this pythonism.

Work related to #10233


# User-Facing Changes
Breaking change as this turns `int * list` or `list * int` into hard
errors.

# Tests + Formatting
Remove the associated test
2023-09-13 10:43:49 +12:00
Stefan Holderbach
e90b099622
Use slices directly instead of &Vec (#10328)
Simplifies the signature, makes it more flexible.
Detected a few unnecessary allocations in the process.
2023-09-12 11:38:20 +08:00
Jakub Žádník
d618b60d9e
Remove leftover const eval file (#10324) 2023-09-11 21:30:38 +03:00
dependabot[bot]
513186c390
Bump bytesize from 1.2.0 to 1.3.0 (#10306) 2023-09-11 09:55:21 +00:00
dependabot[bot]
eeaa65c8af
Bump itertools from 0.10.5 to 0.11.0 (#9524) 2023-09-08 23:12:45 +00:00
nibon7
5ad3bfa31b
Auto format let-else block (#10214)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
rustfmt 1.6.0 has added support for formatting [let-else
statements](https://doc.rust-lang.org/rust-by-example/flow_control/let_else.html)

See https://github.com/rust-lang/rustfmt/blob/master/CHANGELOG.md#added

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2023-09-04 19:42:31 +12:00
Horasal
e5145358eb
treat path contains '?' as pattern (#10142)
Fix https://github.com/nushell/nushell/issues/10136

# Description
Current nushell only handle path containing '*' as match pattern and
treat '?' as just normal path.
This pr makes path containing '?' is also processed as pattern.

🔴 **Concerns: Need to design/comfirm a consistent rule to handle
dirs/files with '?' in their names.**

Currently:

- if no dir has exactly same name with pattern, it will print the list
of matched directories
- if pattern exactly matches an empty dir's name, it will just print the
empty dir's content ( i.e. `[]`)
- if pattern exactly matches an dir's name, it will perform pattern
match and print all the dir contains

e.g.
```bash
mkdir src
ls s?c 
```

| name | type | size   | modified                                      |
| ---- | ---- | ------ | --------------------------------------------- |
| src  | dir  | 1.1 KB | Tue, 29 Aug 2023 07:39:41 +0900 (9 hours ago) |

-----------

```bash
mkdir src
mkdir scc
mkdir scs
ls s?c
```

| name | type | size | modified |
| ---- | ---- | ------ |
------------------------------------------------ |
| scc | dir | 64 B | Tue, 29 Aug 2023 16:55:31 +0900 (14 seconds ago) |
| src | dir | 1.1 KB | Tue, 29 Aug 2023 07:39:41 +0900 (9 hours ago) |

-----------

```bash
mkdir  s?c
ls s?c
```

print empty (i.e. ls of dir `s?c`)

-----------

```bash
mkdir -p  s?c/test
ls s?c
```
|name|type|size|modified|
|-|-|-|-|
|s?c/test|dir|64 B|Tue, 29 Aug 2023 16:47:53 +0900 (2 minutes ago)|
|src/bytes|dir|480 B|Fri, 25 Aug 2023 17:43:52 +0900 (3 days ago)|
|src/charting|dir|160 B|Fri, 25 Aug 2023 17:43:52 +0900 (3 days ago)|
|src/conversions|dir|160 B|Fri, 25 Aug 2023 17:43:52 +0900 (3 days ago)|

-----------

# User-Facing Changes

User will be able to use '?' to match directory/file.

# Tests + Formatting

- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`

# After Submitting

None

---------

Co-authored-by: Horasal <horsal@horsal.dev>
2023-09-03 19:25:00 -05:00
Horasal
dac32557cd
prevent crash when use redirection with let/mut (#10139)
Fix #9992 

I mistakenly messed up https://github.com/nushell/nushell/pull/10118 and
this is a cleaned version.

# Description

* This pr changes the panic to errors while parsing `let`, now user will
get the following errors:
<img width="395" alt="scr"
src="https://github.com/nushell/nushell/assets/1991933/4b39ac14-cd1f-47b3-9490-81009ca42717">
<img width="394" alt="scr"
src="https://github.com/nushell/nushell/assets/1991933/71ce33ad-f4d0-4132-828f-9674b9603556">
<img width="440" alt="scr"
src="https://github.com/nushell/nushell/assets/1991933/257eab4d-1a72-42db-b09e-f42bef33d2ec">

* `out+err>` is cached by `parse_expression` but not this, which may be
a potential problem.
* `Commond(None, ..)` remains panic for future bug report because I
don't actually know when/how does it happen

# User-Facing Changes

Nushell won't crash when user typing `let a = 1 err> ...`

# Tests + Formatting

- `cargo fmt --all -- --check` : OK
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` : OK
- `cargo test --workspace` : OK
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` : OK

# After Submitting

None

Co-authored-by: Horasal <horsal@horsal.dev>
2023-09-03 19:21:45 -05:00
JT
6cdfee3573
Move Value to helpers, separate span call (#10121)
# Description

As part of the refactor to split spans off of Value, this moves to using
helper functions to create values, and using `.span()` instead of
matching span out of Value directly.

Hoping to get a few more helping hands to finish this, as there are a
lot of commands to update :)

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
Co-authored-by: WindSoilder <windsoilder@outlook.com>
2023-09-03 07:27:29 -07:00
Horasal
b943cbedff
skip comments and eols while parsing pipeline (#10149)
This pr 
- fixes https://github.com/nushell/nushell/issues/10143
- fixes https://github.com/nushell/nushell/issues/5559

# Description

Current `lite_parse` does not handle multiple line comments and eols in
pipeline.
When parsing the following tokens:


| `"abcdefg"` | ` \|` | `# foobar` | ` \n` | `split chars` |
| ------------- | ------------- |------------- |-------------
|------------- |
| [Command] | [Pipe] | [Comment] | [Eol] | [Command] |
| | | Last Token |Current Token | |

`TokenContent::Eol` handler only checks if `last_token` is `Pipe` but it
will be broken if there exist any other thing, e.g. extra `[Comment]` in
this example.

This pr make the following change:

- While parsing `[Eol]`, try to find the last non-comment token as
`last_token`
- Comment is supposed as `[Comment]+` or `([Comment] [Eol])+`
- `[Eol]+` is still parsed just like current nu (i.e. generates
`nothing`).

Notice that this pr is just a quick patch if more comment/eol related
issue occures, `lite_parser` may need a rewrite.

# User-Facing Changes

Now the following pipeline works: 

```bash
1 | # comment
each { |it| $it + 2 } | # comment
math sum
```

Comment will not end the pipeline in interactive mode:

```bash
❯ 1 | # comment   (now enter multiple line mode instead of end)
▶▶ # foo
▶▶ 2
```

# Tests + Formatting

- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`

# After Submitting

None

---------

Co-authored-by: Horasal <horsal@horsal.dev>
2023-08-30 13:24:13 -05:00
Horasal
1f06f8405c
handle empty pipeline while parsing let (fix Issue10083) (#10116)
- fixes #10083 

# Description

nushell crashes in the following 2 condition:

- `let a = {}` , then delete `{`
- `let a = | {}`, then delete `{`

When delete `{` the pipeline becomes empty but current `nu-parser`
assume they are non-empty. This pr adds extra empty check to avoid
crash.


Co-authored-by: Horasal <horsal@horsal.dev>
2023-08-28 13:38:11 +02:00
Jakub Žádník
5ac5b90aed
Allow parse-time evaluation of calls, pipelines and subexpressions (#9499)
Co-authored-by: Antoine Stevan <44101798+amtoine@users.noreply.github.com>
2023-08-26 16:41:29 +03:00
JT
1e3e034021
Spanned Value step 1: span all value cases (#10042)
# Description

This doesn't really do much that the user could see, but it helps get us
ready to do the steps of the refactor to split the span off of Value, so
that values can be spanless. This allows us to have top-level values
that can hold both a Value and a Span, without requiring that all values
have them.

We expect to see significant memory reduction by removing so many
unnecessary spans from values. For example, a table of 100,000 rows and
5 columns would have a savings of ~8megs in just spans that are almost
always duplicated.

# User-Facing Changes

Nothing yet

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect -A clippy::result_large_err` to check that
you're using the standard code style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2023-08-25 08:48:05 +12:00
Ian Manske
8da27a1a09
Create Record type (#10103)
# Description
This PR creates a new `Record` type to reduce duplicate code and
possibly bugs as well. (This is an edited version of #9648.)
- `Record` implements `FromIterator` and `IntoIterator` and so can be
iterated over or collected into. For example, this helps with
conversions to and from (hash)maps. (Also, no more
`cols.iter().zip(vals)`!)
- `Record` has a `push(col, val)` function to help insure that the
number of columns is equal to the number of values. I caught a few
potential bugs thanks to this (e.g. in the `ls` command).
- Finally, this PR also adds a `record!` macro that helps simplify
record creation. It is used like so:
   ```rust
   record! {
       "key1" => some_value,
       "key2" => Value::string("text", span),
       "key3" => Value::int(optional_int.unwrap_or(0), span),
       "key4" => Value::bool(config.setting, span),
   }
   ```
Since macros hinder formatting, etc., the right hand side values should
be relatively short and sweet like the examples above.

Where possible, prefer `record!` or `.collect()` on an iterator instead
of multiple `Record::push`s, since the first two automatically set the
record capacity and do less work overall.

# User-Facing Changes
Besides the changes in `nu-protocol` the only other breaking changes are
to `nu-table::{ExpandedTable::build_map, JustTable::kv_table}`.
2023-08-25 07:50:29 +12:00
Darren Schroeder
3d698b74d8
bump nushell to dev version 0.84.1 (#10101)
# Description

This PR bumps nushell from release version 0.84.0 to dev version 0.84.1.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2023-08-23 15:23:27 -05:00
JT
894e0f7658
bump to 0.84 (#10093) 2023-08-22 21:23:39 +03:00
Jakub Žádník
3148acd3a4
Recursively export constants from modules (#10049)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

https://github.com/nushell/nushell/pull/9773 introduced constants to
modules and allowed to export them, but only within one level. This PR:
* allows recursive exporting of constants from all submodules
* fixes submodule imports in a list import pattern
* makes sure exported constants are actual constants

Should unblock https://github.com/nushell/nushell/pull/9678

### Example:
```nushell
module spam {
    export module eggs {
        export module bacon {
            export const viking = 'eats'
        }
    }
}

use spam 
print $spam.eggs.bacon.viking  # prints 'eats'

use spam [eggs]
print $eggs.bacon.viking  # prints 'eats'

use spam eggs bacon viking
print $viking  # prints 'eats'
```

### Limitation 1:

Considering the above `spam` module, attempting to get `eggs bacon` from
`spam` module doesn't work directly:
```nushell
use spam [ eggs bacon ]  # attempts to load `eggs`, then `bacon`
use spam [ "eggs bacon" ]  # obviously wrong name for a constant, but doesn't work also for commands
```

Workaround (for example):
```nushell
use spam eggs
use eggs [ bacon ]

print $bacon.viking  # prints 'eats'
```

I'm thinking I'll just leave it in, as you can easily work around this.
It is also a limitation of the import pattern in general, not just
constants.

### Limitation 2:

`overlay use` successfully imports the constants, but `overlay hide`
does not hide them, even though it seems to hide normal variables
successfully. This needs more investigation.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

Allows recursive constant exports from submodules.

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect -A clippy::result_large_err` to check that
you're using the standard code style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2023-08-20 14:51:35 +02:00
Jakub Žádník
cdf09abcc0
Allow exporting extern-wrapped (#10025) 2023-08-18 20:45:33 +03:00
Jakub Žádník
c5e59efa4d
Sort entries in scope commands; Fix usage of externs (#10039)
# Description

* All output of `scope` commands is sorted by the "name" column. (`scope
externs` and some other commands had entries in a weird/random order)
* The output of `scope externs` does not have extra newlines (that was
due to wrong usage creation of known externals)
2023-08-17 16:37:01 +02:00
Jakub Žádník
e88a51e930
Refactor scope commands (#10023) 2023-08-17 11:58:38 +03:00
Kiryl Mialeshka
ad49c17eba
fix(nu-parser): do not update plugin.nu file on nu startup (#10007)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description

I've been investigating the [issue
mentioned](https://github.com/nushell/nushell/pull/9976#issuecomment-1673290467)
in my prev pr and I've found that plugin.nu file that is used to cache
plugins signatures gets overwritten on every nushell startup and that
may actually mess up with the file content if 2 or more instances of
nushell will run simultaneously.

To reproduce:
1. register at least 2 plugins in your local nushell
2. remember how many entries you have in plugin.nu with `open
$nu.plugin-path | find nu_plugin`
3. run 
    - either `cargo test` inside nushell repo
- or run smth like this `1..100 | par-each {|it| $"(random integer
1..100)ms" | into duration | sleep $in; nu -c "$nu.plugin-path"}` to
simulate parallel access. This approach is not so reliable to reproduce
as running test but still a good point that it may effect users actually
4. validate that your `plugin.nu` file was stripped

<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

# Solution

In this pr I've refactored the code of handling the `register` command
to minimize code duplications and make sure that overwrite of
`plugin.nu` file is happen only when user calls the command and not on
nu startup

Another option would be to use temp `plugin.nu` when running tests, but
as the issue actually can affect users I've decided to prevent
unnecessary writing at all. Although having isolated `plugin.nu` still
worth of doing

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
It changes the behaviour actually as the call `register <plugin>
<signature>` now doesn't updates `plugin.nu` and just reads signatures
to the memory. But as I understand that kind of call with explicit
signature is meant to use only by nushell itself in the `plugin.nu` file
only. I've asked about it in
[discord](https://discordapp.com/channels/601130461678272522/615962413203718156/1140013448915325018)

<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect -A clippy::result_large_err` to check that
you're using the standard code style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->

Actually, I think the way plugins are stored might be reworked to
prevent or mitigate possible issues further:
- problem with writing to file may still arise if we try to register in
parallel as several instances will write to the same file so the lock
for the file might be required
- using additional parameters to command like `register` to implement
some internal logic could be misleading to the users
- `register` call actually affects global state of nushell that sounds a
little bit inconsistent with immutability and isolation of other parts
of the nu. See issues
[1](https://github.com/nushell/nushell/issues/8581),
[2](https://github.com/nushell/nushell/issues/8960)
2023-08-14 08:39:23 -05:00
dependabot[bot]
02be83efbf
Bump rstest from 0.17.0 to 0.18.1 (#9782) 2023-08-08 17:11:05 +00:00
Bob Hyman
570175f95d
Fix duration type to not report months or years (#9632)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->
This PR should close #8036, #9028 (in the negative) and #9118.

Fix for #9118 is a bit pedantic.  As reported, the issue is:
```
> 2023-05-07T04:08:45+12:00 - 2019-05-10T09:59:12+12:00
3yr 12month 2day 18hr 9min 33sec
```
with this PR, you now get:
```
> 2023-05-07T04:08:45+12:00 - 2019-05-10T09:59:12+12:00
208wk 1day 18hr 9min 33sec
```
Which is strictly correct, but could still fairly be called "weird date
arithmetic".

# Description
* [x] Abide by constraint that Value::Duration remains a number of
nanoseconds with no additional fields.
* [x] `to_string()` only displays weeks .. nanoseconds. Duration doesn't
have base date to compute months or years from.
* [x] `duration | into record` likewise only has fields for weeks ..
nanoseconds.
* [x] `string | into duration` now accepts compound form of duration
to_string() (e.g '2day 3hr`, not just '2day')
* [x] `duration | into string` now works (and produces the same
representation as to_string(), which may be compound).

# User-Facing Changes
## duration -> string -> duration
Now you can "round trip" an arbitrary duration value: convert it to a
string that may include multiple time units (a "compound" value), then
convert that string back into a duration. This required changes to
`string | into duration` and the addition of `duration | into string'.
```
> 2day + 3hr
2day 3hr # the "to_string()" representation (in this case, a compound value)
> 2day + 3hr | into string
2day 3hr # string value
> 2day + 3hr | into string | into duration
2day 3hr # round-trip duration -> string -> duration
```
Note that `to nuon` and `from nuon` already round-tripped durations, but
use a different string representation.

## potentially breaking changes
* string rendering of a duration no longer has 'yr' or 'month' phrases.
* record from `duration | into record` no longer has 'year' or 'month'
fields.
The excess duration is all lumped into the `week` field, which is the
largest time unit you can
convert to without knowing the datetime from which the duration was
calculated.

Scripts that depended on month or year time units on output will need to
be changed.

### Examples
```
> 365day
52wk 1day
## Used to be: 
## 1yr

> 365day | into record
╭──────┬────╮
│ week │ 52 │
│ day  │ 1  │
│ sign │ +  │
╰──────┴────╯

## used to be:
##╭──────┬───╮
##│ year │ 1 │
##│ sign │ + │
##╰──────┴───╯

> (365day + 4wk + 5day + 6hr + 7min + 8sec + 9ms + 10us + 11ns)
56wk 6day 6hr 7min 8sec 9ms 10µs 11ns
## used to be:
## 1yr 1month 3day 6hr 7min 8sec 9ms 10µs 11ns
## which looks reasonable, but was actually only correct in 75% of the years and 25% of the months in the last 4 years.

> (365day + 4wk + 5day + 6hr + 7min + 8sec + 9ms + 10us + 11ns) | into record
╭─────────────┬────╮
│ week        │ 56 │
│ day         │ 6  │
│ hour        │ 6  │
│ minute      │ 7  │
│ second      │ 8  │
│ millisecond │ 9  │
│ microsecond │ 10 │
│ nanosecond  │ 11 │
│ sign        │ +  │
╰─────────────┴────╯
```
Strictly speaking, these changes could break an existing user script.
Losing years and months as time units is arguably a regression in
behavior.

Also, the corrected duration calculation could break an existing script
that was calibrated using the old algorithm.

# Tests + Formatting
```
> toolkit check pr
```
- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->

---------

Co-authored-by: Bob Hyman <bobhy@localhost.localdomain>
2023-08-08 06:24:09 -05:00
mengsuenyan
fea822792f
Fixed the panic when type a statement similar to let f = 'f' $ in the nushell (#9851)
- this PR should close #9596 
- fixes #9596 
- this PR should close #9826 
- fixes #9826 

fixed the following bugs:
```nu
# type following statements in the nushell
let f = 'f' $;
mut f = 'f' $;
const f = 'f' $;

# then remove variable f, it will panics
let = 'f' $;
mut  = 'f' $;
const = 'f' $;
```
2023-08-02 04:21:40 +12:00
WindSoilder
f6033ac5af
Module: support defining const and use const variables inside of function (#9773)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
Relative: #8248 

After this pr, user can define const variable inside a module.

![image](https://github.com/nushell/nushell/assets/22256154/e3e03e56-c4b5-4144-a944-d1b20bec1cbd)

And user can export const variables, the following screenshot shows how
it works (it follows
https://github.com/nushell/nushell/issues/8248#issuecomment-1637442612):

![image](https://github.com/nushell/nushell/assets/22256154/b2c14760-3f27-41cc-af77-af70a4367f2a)

## About the change
1. To make module support const, we need to change `parse_module_block`
to support `const` keyword.
2. To suport export `const`, we need to make module tracking variables,
so we add `variables` attribute to `Module`
3. During eval, the const variable may not exists in `stack`, because we
don't eval `const` when we define a module, so we need to find variables
which are already registered in `engine_state`

## One more thing to note about the const value.
Consider the following code
```
module foo { const b = 3; export def bar [] { $b } }
use foo bar
const b = 4;
bar
```
The result will be 3 (which is defined in module) rather than 4. I think
it's expected behavior.

It's something like [dynamic
binding](https://www.gnu.org/software/emacs/manual/html_node/elisp/Dynamic-Binding-Tips.html)
vs [lexical
binding](https://www.gnu.org/software/emacs/manual/html_node/elisp/Lexical-Binding.html)
in lisp like language, and lexical binding should be right behavior
which generates more predicable result, and it doesn't introduce really
subtle bugs in nushell code.

What if user want dynamic-binding?(For example: the example code returns
`4`)
There is no way to do this, user should consider passing the value as
argument to custom command rather than const.

## TODO
- [X] adding tests for the feature.
- [X] support export const out of module to use.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect -A clippy::result_large_err` to check that
you're using the standard code style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2023-08-01 07:09:52 +08:00
Darren Schroeder
955de76116
bump to dev version 0.83.2 (#9866)
# Description

This PR bumps the development version of nushell to version 0.83.2.
2023-07-30 22:16:57 +02:00