Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: correct typed-nil handling #1891

Draft
wants to merge 1 commit into
base: fix/maxwell/type_comparison
Choose a base branch
from

Conversation

ltzmaxwell
Copy link
Contributor

@ltzmaxwell ltzmaxwell commented Apr 4, 2024

don't merge.

the dependency relationship: #1890 <- this one.

@ltzmaxwell ltzmaxwell requested review from jaekwon, piux2, thehowl, moul and a team as code owners April 4, 2024 17:57
@github-actions github-actions bot added 🧾 package/realm Tag used for new Realms or Packages. 📦 🤖 gnovm Issues or PRs gnovm related labels Apr 4, 2024
@ltzmaxwell ltzmaxwell marked this pull request as draft April 4, 2024 17:59
@ltzmaxwell ltzmaxwell mentioned this pull request Apr 4, 2024
jaekwon added a commit that referenced this pull request Jun 19, 2024
**Pinned Update:**

The original #1426 is now divided
into 4 parts, with the dependency relationship being:
#1426 <
#1775,
#1426 <-
https://github.com/gnolang/gno/pull/1890<-
#1891.

Among these, the main part, #1426,
has been supplemented and optimized for the missing parts in the type
checks of the original implementation, specifically as follows:

- A new layer for type check is added(type_check.go). during the
preprocess stage, the compatibility of operators and operands in
expressions is checked, such as 1 - "a". This part used to be
implemented as a runtime error, but now it is checked in type_check.go;
 
- Modifications have been made to checkOrConvertType to add conversion
checks for constants, such as int(1) + int64(1), which previously would
not trigger a compile-time error;

- Refined and improved several aspects of the handling logic for
BinaryExpr during the preprocessing stage.
 
- The existing checkType has been renamed to assertAssignableTo.

==========================update complete=======================

### Problem Definition

Please proceed to #1424.

======update:
fix #1462 , tests located in `gnovm/tests/files/type2`.
this issue is fixed since they share the same contexts of type check and
conversion.

briefly for #1462, type of shift expression (or any composed expression
involved shift expression) will be determined in the context they are
used if they are untyped, also can be mutated by explicitly conversion
with a `type call`.


==========================================================================================


### Overview of Solution
#### checkOperandWithOp function:
**Purpose**: Newly introduced to evaluate operand compatibility before
deep type analysis.
**Functionality**: Employs predefined rules to quickly identify
incompatible patterns (e.g., "a" << 1 is flagged as incompatible).
**Advantage**: Prevents unnecessary processing by checkOrConvertType for
clear mismatches.

#### checkOrConvertType function:
**Role**: Engages after checkOperandWithOp's clearance. It's the hub for
core type checking and conversion.
**Key Improvement**: Enhanced handling of const conversions by limiting
it within a certain range.
**Example**: In cases like int(1) + int(8), the issue of unregulated
const conversion is addressed.
**Constraints**: Mandatory const conversion is now limited to specific
scenarios (e.g., explicit conversion, operand in array/slice index, RHS
of a shift expression).

### Specific Problems Solved

1. **assignable and sameType check:**
This code should output "something else". the root cause for this is
Error(0) is assignable to errCmp since it satisfies the interface of
error, and result in inequality since the have different concrete type
in runtime.
Thanks @jaekwon for pointing out my mistake and give an improved version
of this.

```go
package main

import (
    "errors"
    "strconv"
)

type Error int64

func (e Error) Error() string {
    return "error: " + strconv.Itoa(int(e))
}

var errCmp = errors.New("XXXX")

func main() {
    if Error(0) == errCmp {
        println("what the firetruck?")
    } else {
        println("something else")
    }
}
```


2. **Early Incompatibility Detection:**
Conducted during preprocessing, not runtime.
**Example**:
```go
package main
func main() {
    println(1 / "a") // Detects incompatibility early.
}
```
```go
func main() {
    println(int(1) == int8(1))  // this is checked before checkOrConvertType if LHS and RHS are both typed.
}
```

~~3. **Implicit Conversion:**~~(this is split out)
~~Focus: Ensuring accurate conversions, particularly unnamed to named
types.~~
~~Example:~~
~~```go~~
~~package main~~
~~type word uint~~
~~type nat []word~~
~~func (n nat) add() bool {~~
   ~~ return true~~
~~}
~~func Gen() nat {~~
    ~~n := []word{0}~~
    ~~return n~~
~~}~~
~~func main() {~~
    ~~r := Gen()~~
    ~~switch r.(type) {~~
   ~~ case nat:~~
        ~~println("nat")~~
        ~~println(r.add())~~
    ~~default:~~
        ~~println("should not happen")~~
   ~~ }~~
~~}~~
~~```~~
~~4. **Type of Shift Expressions:**~~
~~**Context**: Determines the type based on usage context and explicit
conversions.~~
~~**Implementation**: Additional checks in assignStmt, callExpr for
potential untyped shift expressions (or else expressions with untyped
shift expression embedded)~~~~appear, e.g. uint64(1 << x). This will
trigger a potentially recursive check&convert until the shift expr got
its final type.~~

### Conclusion:
This PR enhances the type check workflow and addresses previously
overlooked aspects, resolving a variety of type-related issues.

---------

Co-authored-by: Morgan <git@howl.moe>
Co-authored-by: jaekwon <jae@tendermint.com>
@ltzmaxwell ltzmaxwell changed the base branch from master to fix/maxwell/type_comparison July 30, 2024 16:23
Copy link

codecov bot commented Jul 30, 2024

Codecov Report

Attention: Patch coverage is 66.66667% with 4 lines in your changes missing coverage. Please review.

Project coverage is 59.95%. Comparing base (699c022) to head (49dcc41).

Files Patch % Lines
gnovm/pkg/gnolang/preprocess.go 55.55% 4 Missing ⚠️
Additional details and impacted files
@@                     Coverage Diff                      @@
##           fix/maxwell/type_comparison    #1891   +/-   ##
============================================================
  Coverage                        59.94%   59.95%           
============================================================
  Files                              560      560           
  Lines                            77225    77236   +11     
============================================================
+ Hits                             46296    46308   +12     
  Misses                           27408    27408           
+ Partials                          3521     3520    -1     
Flag Coverage Δ
contribs/gnodev 61.40% <ø> (ø)
contribs/gnofaucet 14.46% <ø> (ø)
gno.land 64.15% <ø> (ø)
gnovm 64.20% <66.66%> (-0.01%) ⬇️
misc/genstd 80.54% <ø> (ø)
misc/logos 20.23% <ø> (+0.35%) ⬆️
tm2 62.05% <ø> (+0.10%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
📦 🤖 gnovm Issues or PRs gnovm related 🧾 package/realm Tag used for new Realms or Packages.
Projects
Status: No status
Status: No status
Status: Triage
Development

Successfully merging this pull request may close these issues.

1 participant