Skip to content

Commit ed8394b

Browse files
committed
pybricksMicropython/lib: handle exceptions when parsing
The new code parsing library raises exceptions when there are syntax errors, so this needs to be handled. Fixes: pybricks/support#755
1 parent d07cbf6 commit ed8394b

File tree

2 files changed

+30
-13
lines changed

2 files changed

+30
-13
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@
44

55
## [Unreleased]
66

7+
### Fixed
8+
- Fixed crash when user program contains syntax error ([support#755]).
9+
10+
[support#755]: https://github.com/pybricks/support/issues/755
11+
712
## [2.0.0-beta.7] - 2022-10-24
813

914
### Fixed

src/pybricksMicropython/lib.ts

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -74,25 +74,37 @@ export function validateFileName(
7474
/**
7575
* Finds modules imported by a Python script.
7676
*
77+
* Returns an empty list if there are syntax errors.
78+
*
7779
* @param py A Python Script.
7880
* @returns A list of the names of modules imported by this file.
7981
*/
8082
export function findImportedModules(py: string): ReadonlySet<string> {
8183
const modules = new Set<string>();
82-
const tree = parse(py);
83-
84-
// find all import statements in the syntax tree and collect imported modules
85-
walk(tree, {
86-
onEnterNode(node, _ancestors) {
87-
if (node.type === 'import') {
88-
for (const name of node.names) {
89-
modules.add(name.path);
84+
85+
try {
86+
const tree = parse(py);
87+
88+
// find all import statements in the syntax tree and collect imported modules
89+
walk(tree, {
90+
onEnterNode(node, _ancestors) {
91+
if (node.type === 'import') {
92+
for (const name of node.names) {
93+
modules.add(name.path);
94+
}
95+
} else if (node.type === 'from') {
96+
modules.add(node.base);
9097
}
91-
} else if (node.type === 'from') {
92-
modules.add(node.base);
93-
}
94-
},
95-
});
98+
},
99+
});
100+
} catch (err) {
101+
// istanbul ignore if
102+
if (process.env.NODE_ENV === 'development') {
103+
console.debug(err);
104+
}
105+
106+
// files with syntax errors are ignored
107+
}
96108

97109
return modules;
98110
}

0 commit comments

Comments
 (0)