Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,29 @@ jobs:
components: rustfmt, clippy

- name: Check formatting
if: github.event_name != 'pull_request'
run: cargo fmt -- --check

- name: Run formatter with auto-fix (PRs only)
if: github.event_name == 'pull_request'
run: |
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"

git fetch origin ${{ github.head_ref }}
git checkout ${{ github.head_ref }}

cargo fmt

if [[ -n $(git status -s) ]]; then
echo "Formatter made automatic fixes"
git add -A
git commit -m "🤖 Auto-format code"
git push origin ${{ github.head_ref }}
else
echo "No formatting fixes needed"
fi

- name: Run clippy
if: github.event_name != 'pull_request'
run: cargo clippy -- -D warnings
Expand All @@ -67,11 +88,9 @@ jobs:

if [[ -n $(git status -s) ]]; then
echo "Clippy made automatic fixes"
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git add -A
git commit -m "🤖 Auto-fix clippy warnings"
git push
git push origin ${{ github.head_ref }}
else
echo "No clippy fixes needed"
# Run clippy again to ensure everything passes
Expand Down Expand Up @@ -107,8 +126,8 @@ jobs:
steps:
- uses: actions/checkout@v4

- name: Install Rust 1.70
uses: dtolnay/rust-toolchain@1.70
- name: Install Rust 1.88.0
uses: dtolnay/rust-toolchain@1.88.0

- name: Check MSRV
run: cargo check --verbose
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ By participating in this project, you agree to abide by our Code of Conduct:

### Prerequisites

- Rust 1.70 or higher
- Rust 1.88 or higher (for 2024 edition and let-chains support)
- Git
- Python 3.8+ (for testing against Python files)

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ cargo install --path .

### Requirements

- Rust 1.70+
- Rust 1.88+ (for 2024 edition and let-chains support)
- Python 3.8+ (for checking Python 3.8+ code)

## 🤝 Contributing
Expand Down
132 changes: 74 additions & 58 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
pub mod python_type;

use std::collections::{HashMap, HashSet};
use python_parser::ast::*;
use std::collections::{HashMap, HashSet};
use std::str::FromStr;

pub use crate::python_type::PythonType;
Expand All @@ -25,15 +25,28 @@ impl std::fmt::Display for TypeCheckError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TypeCheckError::ParseError(msg) => write!(f, "Parse error: {msg}"),
TypeCheckError::UnsupportedAnnotation(msg) => write!(f, "Unsupported annotation: {msg}"),
TypeCheckError::UnsupportedAnnotation(msg) => {
write!(f, "Unsupported annotation: {msg}")
}
TypeCheckError::UnknownType(msg) => write!(f, "Unknown type: {msg}"),
TypeCheckError::TypeMismatch { variable: _, expected, actual, literal_value } => {
TypeCheckError::TypeMismatch {
variable: _,
expected,
actual,
literal_value,
} => {
if let Some(literal) = literal_value {
write!(f, "Type \"Literal[{literal}]\" is not assignable to declared type \"{expected}\"\n \"Literal[{literal}]\" is not assignable to \"{expected}\"")
write!(
f,
"Type \"Literal[{literal}]\" is not assignable to declared type \"{expected}\"\n \"Literal[{literal}]\" is not assignable to \"{expected}\""
)
} else {
write!(f, "Type \"{actual}\" is not assignable to declared type \"{expected}\"\n \"{actual}\" is not assignable to \"{expected}\"")
write!(
f,
"Type \"{actual}\" is not assignable to declared type \"{expected}\"\n \"{actual}\" is not assignable to \"{expected}\""
)
}
},
}
}
}
}
Expand All @@ -54,7 +67,7 @@ impl TypeChecker {
including_implicit: false,
}
}

pub fn with_implicit_checking(mut self) -> Self {
self.including_implicit = true;
self
Expand All @@ -74,11 +87,13 @@ impl TypeChecker {

fn process_statement(&mut self, statement: Statement) -> TypeCheckResult<()> {
match statement {
Statement::TypedAssignment(target, annotation, value) => self.handle_typed_assignment(target, annotation, value)?,
Statement::TypedAssignment(target, annotation, value) => {
self.handle_typed_assignment(target, annotation, value)?
}
Statement::Assignment(lhs, rhs_list) => {
self.handle_untyped_assignment(lhs, rhs_list)?
},
_ => {},
}
_ => {}
}
Ok(())
}
Expand All @@ -90,38 +105,40 @@ impl TypeChecker {
pub fn get_all_variables(&self) -> &HashMap<String, PythonType> {
&self.assigned_variables
}

pub fn handle_typed_assignment(
&mut self,
target: Vec<Expression>,
annotation: Expression,
values: Vec<Expression>,
) -> TypeCheckResult<()> {
let expected_type = self.parse_type_annotation(&annotation)?;

if let Some(value) = values.first()
&& let Some(actual_type) = self.infer_type_from_expression(value)
&& !self.is_assignable(&actual_type, &expected_type)
&& let Some(Expression::Name(var_name)) = target.first() {
let literal_value = self.get_literal_value(value);
return Err(TypeCheckError::TypeMismatch {
variable: var_name.clone(),
expected: expected_type,
actual: actual_type,
literal_value,
});
}

&& !self.is_assignable(&actual_type, &expected_type)
&& let Some(Expression::Name(var_name)) = target.first()
{
let literal_value = self.get_literal_value(value);
return Err(TypeCheckError::TypeMismatch {
variable: var_name.clone(),
expected: expected_type,
actual: actual_type,
literal_value,
});
}

for expr in target {
if let Expression::Name(name) = expr {
self.assigned_variables.insert(name.clone(), expected_type.clone());
self.assigned_variables
.insert(name.clone(), expected_type.clone());
self.explicitly_typed.insert(name);
}
}

Ok(())
}

fn handle_untyped_assignment(
&mut self,
lhs: Vec<Expression>,
Expand All @@ -131,52 +148,53 @@ impl TypeChecker {
Some(v) => v,
None => return Ok(()),
};

let inferred_type = match self.infer_type_from_expression(value) {
Some(t) => t,
None => return Ok(()),
};

for expr in lhs {
let name = match expr {
Expression::Name(n) => n,
_ => continue,
};

if let Some(existing_type) = self.get_enforced_type(&name)
&& !self.is_assignable(&inferred_type, existing_type) {
return Err(TypeCheckError::TypeMismatch {
variable: name.clone(),
expected: existing_type.clone(),
actual: inferred_type.clone(),
literal_value: self.get_literal_value(value),
});
}

&& !self.is_assignable(&inferred_type, existing_type)
{
return Err(TypeCheckError::TypeMismatch {
variable: name.clone(),
expected: existing_type.clone(),
actual: inferred_type.clone(),
literal_value: self.get_literal_value(value),
});
}

self.assigned_variables.insert(name, inferred_type.clone());
}

Ok(())
}

fn get_enforced_type(&self, name: &str) -> Option<&PythonType> {
if self.explicitly_typed.contains(name) || self.including_implicit {
self.assigned_variables.get(name)
} else {
None
}
}

fn parse_type_annotation(&self, annotation: &Expression) -> TypeCheckResult<PythonType> {
match annotation {
Expression::Name(type_name) => {
PythonType::from_str(type_name)
.map_err(|_| TypeCheckError::UnknownType(type_name.clone()))
}
_ => Err(TypeCheckError::UnsupportedAnnotation(format!("{annotation:?}")))
Expression::Name(type_name) => PythonType::from_str(type_name)
.map_err(|_| TypeCheckError::UnknownType(type_name.clone())),
_ => Err(TypeCheckError::UnsupportedAnnotation(format!(
"{annotation:?}"
))),
}
}

fn infer_type_from_expression(&self, expr: &Expression) -> Option<PythonType> {
match expr {
Expression::Int(_) => Some(PythonType::Int),
Expand All @@ -186,34 +204,33 @@ impl TypeChecker {
Expression::ListLiteral(_) => Some(PythonType::List),
Expression::DictLiteral(_) => Some(PythonType::Dict),
Expression::TupleLiteral(_) => Some(PythonType::Tuple),
_ => None
_ => None,
}
}

fn get_literal_value(&self, expr: &Expression) -> Option<String> {
match expr {
Expression::Int(n) => Some(format!("{n}")),
Expression::String(pystrings) => {
if !pystrings.is_empty() {
let content: String = pystrings.iter()
.map(|s| {
format!("{:?}", s.content).trim_matches('"').to_string()
})
let content: String = pystrings
.iter()
.map(|s| format!("{:?}", s.content).trim_matches('"').to_string())
.collect();
Some(format!("'{content}'"))
} else {
Some("''".to_string())
}
},
_ => None
}
_ => None,
}
}

fn is_assignable(&self, actual: &PythonType, expected: &PythonType) -> bool {
if actual == expected {
return true;
}

matches!((actual, expected), (PythonType::Bool, PythonType::Int))
}
}
Expand All @@ -223,4 +240,3 @@ impl Default for TypeChecker {
Self::new()
}
}

Loading