shape_ast/parser/
modules.rs1use crate::error::{Result, ShapeError};
4use crate::parser::pair_location;
5use pest::iterators::Pair;
6
7use crate::ast::{
8 ExportItem, ExportSpec, ExportStmt, ImportItems, ImportSpec, ImportStmt, Item, ModuleDecl,
9};
10use crate::parser::{Rule, functions, items, pair_span};
11
12pub fn parse_import_stmt(pair: Pair<Rule>) -> Result<ImportStmt> {
19 let pair_loc = pair_location(&pair);
20 let mut inner = pair.into_inner();
21 let first = inner.next().ok_or_else(|| ShapeError::ParseError {
22 message: "invalid import statement".to_string(),
23 location: Some(pair_loc.clone()),
24 })?;
25 let first_str = first.as_str();
26 let first_rule = first.as_rule();
27
28 match first_rule {
30 Rule::module_path => {
31 let module_path = first_str.to_string();
32 match inner.next() {
33 Some(pair) if pair.as_rule() == Rule::import_item_list => {
34 let specs = parse_import_item_list(pair)?;
36 Ok(ImportStmt {
37 items: ImportItems::Named(specs),
38 from: module_path,
39 })
40 }
41 Some(pair) if pair.as_rule() == Rule::ident => {
42 let alias = pair.as_str().to_string();
44 let local_name = module_path
45 .rsplit("::")
46 .next()
47 .unwrap_or(module_path.as_str())
48 .to_string();
49 Ok(ImportStmt {
50 items: ImportItems::Namespace {
51 name: local_name,
52 alias: Some(alias),
53 },
54 from: module_path,
55 })
56 }
57 None => {
58 let local_name = module_path
60 .rsplit("::")
61 .next()
62 .unwrap_or(module_path.as_str())
63 .to_string();
64 Ok(ImportStmt {
65 items: ImportItems::Namespace {
66 name: local_name,
67 alias: None,
68 },
69 from: module_path,
70 })
71 }
72 _ => Err(ShapeError::ParseError {
73 message: "unexpected token in use statement".to_string(),
74 location: Some(pair_loc),
75 }),
76 }
77 }
78 _ => Err(ShapeError::ParseError {
79 message: format!(
80 "unexpected token in import statement: {:?} '{}'",
81 first_rule, first_str
82 ),
83 location: Some(pair_loc.with_hint("use 'from path use { ... }' or 'use path'")),
84 }),
85 }
86}
87
88fn parse_import_item_list(pair: Pair<Rule>) -> Result<Vec<ImportSpec>> {
90 let mut imports = Vec::new();
91
92 for item_pair in pair.into_inner() {
93 if item_pair.as_rule() == Rule::import_item {
94 imports.push(parse_import_item(item_pair)?);
95 }
96 }
97
98 Ok(imports)
99}
100
101fn parse_import_item(pair: Pair<Rule>) -> Result<ImportSpec> {
103 let pair_loc = pair_location(&pair);
104 let mut inner = pair.into_inner();
105
106 let item_pair = inner.next().ok_or_else(|| ShapeError::ParseError {
107 message: "expected import item name".to_string(),
108 location: Some(pair_loc.clone()),
109 })?;
110
111 match item_pair.as_rule() {
112 Rule::annotation_import_item => {
113 let mut annotation_inner = item_pair.into_inner();
114 let name_pair = annotation_inner
115 .next()
116 .ok_or_else(|| ShapeError::ParseError {
117 message: "expected annotation import name".to_string(),
118 location: Some(pair_loc.clone()),
119 })?;
120 Ok(ImportSpec {
121 name: name_pair.as_str().to_string(),
122 alias: None,
123 is_annotation: true,
124 })
125 }
126 Rule::regular_import_item => {
127 let mut regular_inner = item_pair.into_inner();
128 let name_pair = regular_inner.next().ok_or_else(|| ShapeError::ParseError {
129 message: "expected import item name".to_string(),
130 location: Some(pair_loc.clone()),
131 })?;
132 Ok(ImportSpec {
133 name: name_pair.as_str().to_string(),
134 alias: regular_inner.next().map(|p| p.as_str().to_string()),
135 is_annotation: false,
136 })
137 }
138 _ => Err(ShapeError::ParseError {
139 message: format!("unexpected import item: {:?}", item_pair.as_rule()),
140 location: Some(pair_location(&item_pair)),
141 }),
142 }
143}
144
145pub fn parse_export_item(pair: Pair<Rule>) -> Result<ExportStmt> {
147 let pair_loc = pair_location(&pair);
148 let mut inner = pair.into_inner();
149
150 let next_pair = inner.next().ok_or_else(|| ShapeError::ParseError {
152 message: "expected pub item content".to_string(),
153 location: Some(
154 pair_loc
155 .clone()
156 .with_hint("use 'pub fn', 'pub enum', 'pub type', or 'pub { name }'"),
157 ),
158 })?;
159
160 let item = match next_pair.as_rule() {
161 Rule::foreign_function_def => {
162 ExportItem::ForeignFunction(functions::parse_foreign_function_def(next_pair)?)
163 }
164 Rule::extern_native_function_def => {
165 ExportItem::ForeignFunction(functions::parse_extern_native_function_def(next_pair)?)
166 }
167 Rule::function_def => ExportItem::Function(functions::parse_function_def(next_pair)?),
168 Rule::builtin_function_decl => {
169 ExportItem::BuiltinFunction(functions::parse_builtin_function_decl(next_pair)?)
170 }
171 Rule::builtin_type_decl => {
172 ExportItem::BuiltinType(crate::parser::types::parse_builtin_type_decl(next_pair)?)
173 }
174 Rule::type_alias_def => {
175 ExportItem::TypeAlias(crate::parser::types::parse_type_alias_def(next_pair)?)
176 }
177 Rule::enum_def => ExportItem::Enum(crate::parser::types::parse_enum_def(next_pair)?),
178 Rule::struct_type_def => {
179 ExportItem::Struct(crate::parser::types::parse_struct_type_def(next_pair)?)
180 }
181 Rule::native_struct_type_def => ExportItem::Struct(
182 crate::parser::types::parse_native_struct_type_def(next_pair)?,
183 ),
184 Rule::trait_def => ExportItem::Trait(crate::parser::types::parse_trait_def(next_pair)?),
185 Rule::annotation_def => {
186 ExportItem::Annotation(crate::parser::extensions::parse_annotation_def(next_pair)?)
187 }
188 Rule::variable_decl => {
189 let var_decl = items::parse_variable_decl(next_pair.clone())?;
190 match var_decl.pattern.as_identifier() {
191 Some(name) => {
192 let item = ExportItem::Named(vec![ExportSpec {
193 name: name.to_string(),
194 alias: None,
195 }]);
196 return Ok(ExportStmt {
197 item,
198 source_decl: Some(var_decl),
199 });
200 }
201 None => {
202 return Err(ShapeError::ParseError {
203 message: "destructuring patterns are not supported in pub declarations"
204 .to_string(),
205 location: Some(
206 pair_location(&next_pair)
207 .with_hint("use a simple name: 'pub let name = value'"),
208 ),
209 });
210 }
211 }
212 }
213 Rule::export_spec_list => {
214 let specs = parse_export_spec_list(next_pair)?;
215 ExportItem::Named(specs)
216 }
217 _ => {
218 return Err(ShapeError::ParseError {
219 message: format!("unexpected pub item type: {:?}", next_pair.as_rule()),
220 location: Some(pair_location(&next_pair)),
221 });
222 }
223 };
224
225 Ok(ExportStmt {
226 item,
227 source_decl: None,
228 })
229}
230
231fn parse_export_spec_list(pair: Pair<Rule>) -> Result<Vec<ExportSpec>> {
233 let mut specs = Vec::new();
234
235 for spec_pair in pair.into_inner() {
236 if spec_pair.as_rule() == Rule::export_spec {
237 specs.push(parse_export_spec(spec_pair)?);
238 }
239 }
240
241 Ok(specs)
242}
243
244fn parse_export_spec(pair: Pair<Rule>) -> Result<ExportSpec> {
246 let pair_loc = pair_location(&pair);
247 let mut inner = pair.into_inner();
248
249 let name_pair = inner.next().ok_or_else(|| ShapeError::ParseError {
250 message: "expected export specification name".to_string(),
251 location: Some(pair_loc),
252 })?;
253 let name = name_pair.as_str().to_string();
254 let alias = inner.next().map(|p| p.as_str().to_string());
255
256 Ok(ExportSpec { name, alias })
257}
258
259pub fn parse_module_decl(pair: Pair<Rule>) -> Result<ModuleDecl> {
261 let pair_loc = pair_location(&pair);
262 let mut annotations = Vec::new();
263 let mut name: Option<String> = None;
264 let mut name_span = crate::ast::Span::DUMMY;
265 let mut items_out: Vec<Item> = Vec::new();
266
267 for part in pair.into_inner() {
268 match part.as_rule() {
269 Rule::annotations => {
270 annotations = functions::parse_annotations(part)?;
271 }
272 Rule::ident => {
273 if name.is_none() {
274 name = Some(part.as_str().to_string());
275 name_span = pair_span(&part);
276 }
277 }
278 Rule::item => {
279 items_out.push(crate::parser::parse_item(part)?);
280 }
281 Rule::item_recovery => {
282 let span = part.as_span();
283 let text = part.as_str().trim();
284 let preview = if text.len() > 40 {
285 format!("{}...", &text[..40])
286 } else {
287 text.to_string()
288 };
289 return Err(ShapeError::ParseError {
290 message: format!("Syntax error in module body near: {}", preview),
291 location: Some(pair_location(&part).with_length(span.end() - span.start())),
292 });
293 }
294 _ => {}
295 }
296 }
297
298 let name = name.ok_or_else(|| ShapeError::ParseError {
299 message: "missing module name".to_string(),
300 location: Some(pair_loc),
301 })?;
302
303 Ok(ModuleDecl {
304 name,
305 name_span,
306 doc_comment: None,
307 annotations,
308 items: items_out,
309 })
310}