Skip to content

Commit cbc4cb2

Browse files
authored
Merge pull request #16 from youknowone/ast-int
Give identifier and int ast types
2 parents d495cd9 + 6fa3d0f commit cbc4cb2

File tree

88 files changed

+3268
-2295
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

88 files changed

+3268
-2295
lines changed

ast/asdl_rs.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,21 +17,26 @@
1717
AUTO_GEN_MESSAGE = "// File automatically generated by {}.\n\n"
1818

1919
builtin_type_mapping = {
20-
"identifier": "Ident",
20+
"identifier": "Identifier",
2121
"string": "String",
22-
"int": "u32",
22+
"int": "Int",
2323
"constant": "Constant",
2424
}
2525
assert builtin_type_mapping.keys() == asdl.builtin_types
2626

27+
builtin_int_mapping = {
28+
"simple": "bool",
29+
"is_async": "bool",
30+
}
2731

2832
def rust_type_name(name):
2933
"""Return a string for the C name of the type.
3034
3135
This function special cases the default types provided by asdl.
3236
"""
3337
if name in asdl.builtin_types:
34-
return builtin_type_mapping[name]
38+
builtin = builtin_type_mapping[name]
39+
return builtin
3540
elif name.islower():
3641
return "".join(part.capitalize() for part in name.split("_"))
3742
else:
@@ -355,6 +360,8 @@ def visitField(self, field, parent, vis, depth, constructor=None):
355360
typ = f"Option<{typ}>"
356361
if field.seq:
357362
typ = f"Vec<{typ}>"
363+
if typ == "Int":
364+
typ = builtin_int_mapping.get(field.name, typ)
358365
name = rust_field(field.name)
359366
self.emit(f"{vis}{name}: {typ},", depth)
360367

ast/src/attributed.rs

Lines changed: 0 additions & 76 deletions
This file was deleted.

ast/src/builtin.rs

Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
//! `builtin_types` in asdl.py and Attributed
2+
3+
use num_bigint::BigInt;
4+
use rustpython_parser_core::text_size::{TextRange, TextSize};
5+
6+
pub type String = std::string::String;
7+
8+
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
9+
pub struct Identifier(String);
10+
11+
impl Identifier {
12+
#[inline]
13+
pub fn new(s: impl Into<String>) -> Self {
14+
Self(s.into())
15+
}
16+
#[inline]
17+
pub fn as_str(&self) -> &str {
18+
self.0.as_str()
19+
}
20+
}
21+
22+
impl std::string::ToString for Identifier {
23+
#[inline]
24+
fn to_string(&self) -> String {
25+
self.0.clone()
26+
}
27+
}
28+
29+
impl From<Identifier> for String {
30+
#[inline]
31+
fn from(id: Identifier) -> String {
32+
id.0
33+
}
34+
}
35+
36+
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
37+
pub struct Int(u32);
38+
39+
impl Int {
40+
pub fn new(i: u32) -> Self {
41+
Self(i)
42+
}
43+
pub fn new_bool(i: bool) -> Self {
44+
Self(i as u32)
45+
}
46+
pub fn to_u32(&self) -> u32 {
47+
self.0
48+
}
49+
pub fn to_bool(&self) -> bool {
50+
self.0 > 0
51+
}
52+
}
53+
54+
#[derive(Clone, Debug, PartialEq)]
55+
pub enum Constant {
56+
None,
57+
Bool(bool),
58+
Str(String),
59+
Bytes(Vec<u8>),
60+
Int(BigInt),
61+
Tuple(Vec<Constant>),
62+
Float(f64),
63+
Complex { real: f64, imag: f64 },
64+
Ellipsis,
65+
}
66+
67+
impl From<String> for Constant {
68+
fn from(s: String) -> Constant {
69+
Self::Str(s)
70+
}
71+
}
72+
impl From<Vec<u8>> for Constant {
73+
fn from(b: Vec<u8>) -> Constant {
74+
Self::Bytes(b)
75+
}
76+
}
77+
impl From<bool> for Constant {
78+
fn from(b: bool) -> Constant {
79+
Self::Bool(b)
80+
}
81+
}
82+
impl From<BigInt> for Constant {
83+
fn from(i: BigInt) -> Constant {
84+
Self::Int(i)
85+
}
86+
}
87+
88+
#[cfg(feature = "rustpython-literal")]
89+
impl std::fmt::Display for Constant {
90+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91+
match self {
92+
Constant::None => f.pad("None"),
93+
Constant::Bool(b) => f.pad(if *b { "True" } else { "False" }),
94+
Constant::Str(s) => rustpython_literal::escape::UnicodeEscape::new_repr(s.as_str())
95+
.str_repr()
96+
.write(f),
97+
Constant::Bytes(b) => {
98+
let escape = rustpython_literal::escape::AsciiEscape::new_repr(b);
99+
let repr = escape.bytes_repr().to_string().unwrap();
100+
f.pad(&repr)
101+
}
102+
Constant::Int(i) => i.fmt(f),
103+
Constant::Tuple(tup) => {
104+
if let [elt] = &**tup {
105+
write!(f, "({elt},)")
106+
} else {
107+
f.write_str("(")?;
108+
for (i, elt) in tup.iter().enumerate() {
109+
if i != 0 {
110+
f.write_str(", ")?;
111+
}
112+
elt.fmt(f)?;
113+
}
114+
f.write_str(")")
115+
}
116+
}
117+
Constant::Float(fp) => f.pad(&rustpython_literal::float::to_string(*fp)),
118+
Constant::Complex { real, imag } => {
119+
if *real == 0.0 {
120+
write!(f, "{imag}j")
121+
} else {
122+
write!(f, "({real}{imag:+}j)")
123+
}
124+
}
125+
Constant::Ellipsis => f.pad("..."),
126+
}
127+
}
128+
}
129+
130+
#[derive(Clone, Debug, PartialEq)]
131+
pub struct Attributed<T, U = ()> {
132+
pub range: TextRange,
133+
pub custom: U,
134+
pub node: T,
135+
}
136+
137+
impl<T, U> Attributed<T, U> {
138+
/// Returns the node
139+
#[inline]
140+
pub fn node(&self) -> &T {
141+
&self.node
142+
}
143+
144+
/// Returns the `range` of the node. The range offsets are absolute to the start of the document.
145+
#[inline]
146+
pub const fn range(&self) -> TextRange {
147+
self.range
148+
}
149+
150+
/// Returns the absolute start position of the node from the beginning of the document.
151+
#[inline]
152+
pub const fn start(&self) -> TextSize {
153+
self.range.start()
154+
}
155+
156+
/// Returns the absolute position at which the node ends in the source document.
157+
#[inline]
158+
pub const fn end(&self) -> TextSize {
159+
self.range.end()
160+
}
161+
}
162+
163+
impl<T> Attributed<T, ()> {
164+
/// Creates a new node that spans the position specified by `range`.
165+
pub fn new(range: impl Into<TextRange>, node: T) -> Self {
166+
Self {
167+
range: range.into(),
168+
custom: (),
169+
node,
170+
}
171+
}
172+
173+
/// Consumes self and returns the node.
174+
#[inline]
175+
pub fn into_node(self) -> T {
176+
self.node
177+
}
178+
}
179+
180+
impl<T, U> std::ops::Deref for Attributed<T, U> {
181+
type Target = T;
182+
183+
fn deref(&self) -> &Self::Target {
184+
&self.node
185+
}
186+
}

ast/src/fold_helpers.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::{constant, fold::Fold};
1+
use crate::{builtin, fold::Fold};
22

33
pub trait Foldable<T, U> {
44
type Mapped;
@@ -62,4 +62,10 @@ macro_rules! simple_fold {
6262
};
6363
}
6464

65-
simple_fold!(u32, String, bool, constant::Constant);
65+
simple_fold!(
66+
builtin::Int,
67+
builtin::String,
68+
builtin::Identifier,
69+
bool,
70+
builtin::Constant
71+
);

0 commit comments

Comments
 (0)