Skip to content

Commit

Permalink
fix: Index can't make out of bounds and crash
Browse files Browse the repository at this point in the history
  • Loading branch information
davesnx committed Oct 8, 2020
1 parent e52c9be commit 04c6958
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions source/Compiler.re
Original file line number Diff line number Diff line change
Expand Up @@ -153,11 +153,21 @@ let makeEmptyListError = op => {
++ " on an empty array.";
};

let makeAcessingToMissingItem = (accessIndex, length) => {
"Trying to read "
++ Formatting.singleQuotes(
"[" ++ Chalk.bold(string_of_int(accessIndex)) ++ "]",
)
++ " from an array with "
++ string_of_int(length)
++ " elements only.";
};

let head = (json: Json.t) => {
switch (json) {
| `List(list) =>
List.length(list) > 0
? Results.return(Json.index(0, `List(list)))
? Results.return(Json.index(0, json))
: Error(makeEmptyListError("head"))

| _ => Error(makeError("head", json))
Expand All @@ -170,9 +180,9 @@ let tail = (json: Json.t) => {
List.length(list) > 0
? {
let lastIndex = List.length(list) - 1;
Results.return(Json.index(lastIndex, `List(list)));
Results.return(Json.index(lastIndex, json));
}
: Error(makeEmptyListError("head"))
: Error(makeEmptyListError("tail"))
| _ => Error(makeError("tail", json))
};
};
Expand Down Expand Up @@ -203,7 +213,10 @@ let member = (key: string, opt: bool, json: Json.t) => {

let index = (value: int, json: Json.t) => {
switch (json) {
| `List(_list) => Results.return(Json.index(value, json))
| `List(list) =>
List.length(list) > value
? Results.return(Json.index(value, json))
: Error(makeAcessingToMissingItem(value, List.length(list)))
| _ => Error(makeError("[" ++ string_of_int(value) ++ "]", json))
};
};
Expand Down

0 comments on commit 04c6958

Please sign in to comment.