difftreelog
fix string index bounds check
in: master
2 files changed
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth1use std::{2 path::{Path, PathBuf},3 rc::Rc,4};56use gcmodule::Trace;7use jrsonnet_interner::IStr;8use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};9use jrsonnet_types::ValType;10use thiserror::Error;1112use crate::{13 builtin::{format::FormatError, sort::SortError},14 typed::TypeLocError,15};1617#[derive(Error, Debug, Clone, Trace)]18pub enum Error {19 #[error("intrinsic not found: {0}")]20 IntrinsicNotFound(IStr),2122 #[error("operator {0} does not operate on type {1}")]23 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),24 #[error("binary operation {1} {0} {2} is not implemented")]25 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2627 #[error("no top level object in this context")]28 NoTopLevelObjectFound,29 #[error("self is only usable inside objects")]30 CantUseSelfOutsideOfObject,31 #[error("no super found")]32 NoSuperFound,3334 #[error("for loop can only iterate over arrays")]35 InComprehensionCanOnlyIterateOverArray,3637 #[error("array out of bounds: {0} is not within [0,{1})")]38 ArrayBoundsError(usize, usize),3940 #[error("assert failed: {0}")]41 AssertionFailed(IStr),4243 #[error("variable is not defined: {0}")]44 VariableIsNotDefined(IStr),45 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]46 TypeMismatch(&'static str, Vec<ValType>, ValType),47 #[error("no such field: {0}")]48 NoSuchField(IStr),4950 #[error("only functions can be called, got {0}")]51 OnlyFunctionsCanBeCalledGot(ValType),52 #[error("parameter {0} is not defined")]53 UnknownFunctionParameter(String),54 #[error("argument {0} is already bound")]55 BindingParameterASecondTime(IStr),56 #[error("too many args, function has {0}")]57 TooManyArgsFunctionHas(usize),58 #[error("function argument is not passed: {0}")]59 FunctionParameterNotBoundInCall(IStr),6061 #[error("external variable is not defined: {0}")]62 UndefinedExternalVariable(IStr),63 #[error("native is not defined: {0}")]64 UndefinedExternalFunction(IStr),6566 #[error("field name should be string, got {0}")]67 FieldMustBeStringGot(ValType),68 #[error("duplicate field name: {0}")]69 DuplicateFieldName(IStr),7071 #[error("attempted to index array with string {0}")]72 AttemptedIndexAnArrayWithString(IStr),73 #[error("{0} index type should be {1}, got {2}")]74 ValueIndexMustBeTypeGot(ValType, ValType, ValType),75 #[error("cant index into {0}")]76 CantIndexInto(ValType),77 #[error("{0} is not indexable")]78 ValueIsNotIndexable(ValType),7980 #[error("super can't be used standalone")]81 StandaloneSuper,8283 #[error("can't resolve {1} from {0}")]84 ImportFileNotFound(PathBuf, PathBuf),85 #[error("resolved file not found: {0}")]86 ResolvedFileNotFound(PathBuf),87 #[error("imported file is not valid utf-8: {0:?}")]88 ImportBadFileUtf8(PathBuf),89 #[error("import io error: {0}")]90 ImportIo(String),91 #[error("tried to import {1} from {0}, but imports is not supported")]92 ImportNotSupported(PathBuf, PathBuf),93 #[error(94 "syntax error: expected {}, got {:?}",95 .error.expected,96 .source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())97 )]98 ImportSyntaxError {99 #[skip_trace]100 path: Rc<Path>,101 source_code: IStr,102 #[skip_trace]103 error: Box<jrsonnet_parser::ParseError>,104 },105106 #[error("runtime error: {0}")]107 RuntimeError(IStr),108 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]109 StackOverflow,110 #[error("infinite recursion detected")]111 InfiniteRecursionDetected,112 #[error("tried to index by fractional value")]113 FractionalIndex,114 #[error("attempted to divide by zero")]115 DivisionByZero,116117 #[error("string manifest output is not an string")]118 StringManifestOutputIsNotAString,119 #[error("stream manifest output is not an array")]120 StreamManifestOutputIsNotAArray,121 #[error("multi manifest output is not an object")]122 MultiManifestOutputIsNotAObject,123124 #[error("cant recurse stream manifest")]125 StreamManifestOutputCannotBeRecursed,126 #[error("stream manifest output cannot consist of raw strings")]127 StreamManifestCannotNestString,128129 #[error("{0}")]130 ImportCallbackError(String),131 #[error("invalid unicode codepoint: {0}")]132 InvalidUnicodeCodepointGot(u32),133134 #[error("format error: {0}")]135 Format(#[from] FormatError),136 #[error("type error: {0}")]137 TypeError(TypeLocError),138 #[error("sort error: {0}")]139 Sort(#[from] SortError),140141 #[cfg(feature = "anyhow-error")]142 #[error(transparent)]143 Other(Rc<anyhow::Error>),144}145146#[cfg(feature = "anyhow-error")]147impl From<anyhow::Error> for LocError {148 fn from(e: anyhow::Error) -> Self {149 Self::new(Error::Other(Rc::new(e)))150 }151}152153impl From<Error> for LocError {154 fn from(e: Error) -> Self {155 Self::new(e)156 }157}158159#[derive(Clone, Debug, Trace)]160pub struct StackTraceElement {161 pub location: Option<ExprLocation>,162 pub desc: String,163}164#[derive(Debug, Clone, Trace)]165pub struct StackTrace(pub Vec<StackTraceElement>);166167#[derive(Debug, Clone, Trace)]168pub struct LocError(Box<(Error, StackTrace)>);169impl LocError {170 pub fn new(e: Error) -> Self {171 Self(Box::new((e, StackTrace(vec![]))))172 }173174 pub const fn error(&self) -> &Error {175 &(self.0).0176 }177 pub fn error_mut(&mut self) -> &mut Error {178 &mut (self.0).0179 }180 pub const fn trace(&self) -> &StackTrace {181 &(self.0).1182 }183 pub fn trace_mut(&mut self) -> &mut StackTrace {184 &mut (self.0).1185 }186}187188pub type Result<V, E = LocError> = std::result::Result<V, E>;189190#[macro_export]191macro_rules! throw {192 ($e: expr) => {193 return Err($e.into())194 };195}196197#[macro_export]198macro_rules! throw_runtime {199 ($($tt:tt)*) => {200 return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())201 };202}1use std::{2 path::{Path, PathBuf},3 rc::Rc,4};56use gcmodule::Trace;7use jrsonnet_interner::IStr;8use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};9use jrsonnet_types::ValType;10use thiserror::Error;1112use crate::{13 builtin::{format::FormatError, sort::SortError},14 typed::TypeLocError,15};1617#[derive(Error, Debug, Clone, Trace)]18pub enum Error {19 #[error("intrinsic not found: {0}")]20 IntrinsicNotFound(IStr),2122 #[error("operator {0} does not operate on type {1}")]23 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),24 #[error("binary operation {1} {0} {2} is not implemented")]25 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2627 #[error("no top level object in this context")]28 NoTopLevelObjectFound,29 #[error("self is only usable inside objects")]30 CantUseSelfOutsideOfObject,31 #[error("no super found")]32 NoSuperFound,3334 #[error("for loop can only iterate over arrays")]35 InComprehensionCanOnlyIterateOverArray,3637 #[error("array out of bounds: {0} is not within [0,{1})")]38 ArrayBoundsError(usize, usize),39 #[error("string out of bounds: {0} is not within [0,{1})")]40 StringBoundsError(usize, usize),4142 #[error("assert failed: {0}")]43 AssertionFailed(IStr),4445 #[error("variable is not defined: {0}")]46 VariableIsNotDefined(IStr),47 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]48 TypeMismatch(&'static str, Vec<ValType>, ValType),49 #[error("no such field: {0}")]50 NoSuchField(IStr),5152 #[error("only functions can be called, got {0}")]53 OnlyFunctionsCanBeCalledGot(ValType),54 #[error("parameter {0} is not defined")]55 UnknownFunctionParameter(String),56 #[error("argument {0} is already bound")]57 BindingParameterASecondTime(IStr),58 #[error("too many args, function has {0}")]59 TooManyArgsFunctionHas(usize),60 #[error("function argument is not passed: {0}")]61 FunctionParameterNotBoundInCall(IStr),6263 #[error("external variable is not defined: {0}")]64 UndefinedExternalVariable(IStr),65 #[error("native is not defined: {0}")]66 UndefinedExternalFunction(IStr),6768 #[error("field name should be string, got {0}")]69 FieldMustBeStringGot(ValType),70 #[error("duplicate field name: {0}")]71 DuplicateFieldName(IStr),7273 #[error("attempted to index array with string {0}")]74 AttemptedIndexAnArrayWithString(IStr),75 #[error("{0} index type should be {1}, got {2}")]76 ValueIndexMustBeTypeGot(ValType, ValType, ValType),77 #[error("cant index into {0}")]78 CantIndexInto(ValType),79 #[error("{0} is not indexable")]80 ValueIsNotIndexable(ValType),8182 #[error("super can't be used standalone")]83 StandaloneSuper,8485 #[error("can't resolve {1} from {0}")]86 ImportFileNotFound(PathBuf, PathBuf),87 #[error("resolved file not found: {0}")]88 ResolvedFileNotFound(PathBuf),89 #[error("imported file is not valid utf-8: {0:?}")]90 ImportBadFileUtf8(PathBuf),91 #[error("import io error: {0}")]92 ImportIo(String),93 #[error("tried to import {1} from {0}, but imports is not supported")]94 ImportNotSupported(PathBuf, PathBuf),95 #[error(96 "syntax error: expected {}, got {:?}",97 .error.expected,98 .source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())99 )]100 ImportSyntaxError {101 #[skip_trace]102 path: Rc<Path>,103 source_code: IStr,104 #[skip_trace]105 error: Box<jrsonnet_parser::ParseError>,106 },107108 #[error("runtime error: {0}")]109 RuntimeError(IStr),110 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]111 StackOverflow,112 #[error("infinite recursion detected")]113 InfiniteRecursionDetected,114 #[error("tried to index by fractional value")]115 FractionalIndex,116 #[error("attempted to divide by zero")]117 DivisionByZero,118119 #[error("string manifest output is not an string")]120 StringManifestOutputIsNotAString,121 #[error("stream manifest output is not an array")]122 StreamManifestOutputIsNotAArray,123 #[error("multi manifest output is not an object")]124 MultiManifestOutputIsNotAObject,125126 #[error("cant recurse stream manifest")]127 StreamManifestOutputCannotBeRecursed,128 #[error("stream manifest output cannot consist of raw strings")]129 StreamManifestCannotNestString,130131 #[error("{0}")]132 ImportCallbackError(String),133 #[error("invalid unicode codepoint: {0}")]134 InvalidUnicodeCodepointGot(u32),135136 #[error("format error: {0}")]137 Format(#[from] FormatError),138 #[error("type error: {0}")]139 TypeError(TypeLocError),140 #[error("sort error: {0}")]141 Sort(#[from] SortError),142143 #[cfg(feature = "anyhow-error")]144 #[error(transparent)]145 Other(Rc<anyhow::Error>),146}147148#[cfg(feature = "anyhow-error")]149impl From<anyhow::Error> for LocError {150 fn from(e: anyhow::Error) -> Self {151 Self::new(Error::Other(Rc::new(e)))152 }153}154155impl From<Error> for LocError {156 fn from(e: Error) -> Self {157 Self::new(e)158 }159}160161#[derive(Clone, Debug, Trace)]162pub struct StackTraceElement {163 pub location: Option<ExprLocation>,164 pub desc: String,165}166#[derive(Debug, Clone, Trace)]167pub struct StackTrace(pub Vec<StackTraceElement>);168169#[derive(Debug, Clone, Trace)]170pub struct LocError(Box<(Error, StackTrace)>);171impl LocError {172 pub fn new(e: Error) -> Self {173 Self(Box::new((e, StackTrace(vec![]))))174 }175176 pub const fn error(&self) -> &Error {177 &(self.0).0178 }179 pub fn error_mut(&mut self) -> &mut Error {180 &mut (self.0).0181 }182 pub const fn trace(&self) -> &StackTrace {183 &(self.0).1184 }185 pub fn trace_mut(&mut self) -> &mut StackTrace {186 &mut (self.0).1187 }188}189190pub type Result<V, E = LocError> = std::result::Result<V, E>;191192#[macro_export]193macro_rules! throw {194 ($e: expr) => {195 return Err($e.into())196 };197}198199#[macro_export]200macro_rules! throw_runtime {201 ($($tt:tt)*) => {202 return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())203 };204}crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -589,13 +589,19 @@
n.value_type(),
)),
- (Val::Str(s), Val::Num(n)) => Val::Str(
- s.chars()
+ (Val::Str(s), Val::Num(n)) => Val::Str({
+ let v: IStr = s
+ .chars()
.skip(n as usize)
.take(1)
.collect::<String>()
- .into(),
- ),
+ .into();
+ if v.is_empty() {
+ let size = s.chars().count();
+ throw!(StringBoundsError(n as usize, size))
+ }
+ v
+ }),
(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(
ValType::Str,
ValType::Num,