variables.rs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. extern crate solang;
  2. use solang::output;
  3. use solang::{parse_and_resolve, Target};
  4. fn first_error(errors: Vec<output::Output>) -> String {
  5. for m in errors.iter().filter(|m| m.level == output::Level::Error) {
  6. return m.message.to_owned();
  7. }
  8. panic!("no errors detected");
  9. }
  10. #[test]
  11. fn test_variable_errors() {
  12. let (_, errors) = parse_and_resolve(
  13. "contract test {
  14. // solc 0.4.25 compiles this to 30.
  15. function foo() public pure returns (int32) {
  16. int32 a = b + 3;
  17. int32 b = a + 7;
  18. return a * b;
  19. }
  20. }",
  21. &Target::Substrate,
  22. );
  23. assert_eq!(first_error(errors), "`b' is not declared");
  24. }
  25. #[test]
  26. fn test_variable_initializer_errors() {
  27. // cannot read contract storage in constant
  28. let (_, errors) = parse_and_resolve(
  29. "contract test {
  30. uint x = 102;
  31. uint constant y = x + 5;
  32. }",
  33. &Target::Substrate,
  34. );
  35. assert_eq!(
  36. first_error(errors),
  37. "cannot read variable x in constant expression"
  38. );
  39. // cannot read contract storage in constant
  40. let (_, errors) = parse_and_resolve(
  41. "contract test {
  42. function foo() public pure returns (uint) {
  43. return 102;
  44. }
  45. uint constant y = foo() + 5;
  46. }",
  47. &Target::Substrate,
  48. );
  49. assert_eq!(
  50. first_error(errors),
  51. "cannot call function in constant expression"
  52. );
  53. // cannot refer to variable declared later
  54. let (_, errors) = parse_and_resolve(
  55. "contract test {
  56. uint x = y + 102;
  57. uint y = 102;
  58. }",
  59. &Target::Substrate,
  60. );
  61. assert_eq!(first_error(errors), "`y' is not declared");
  62. // cannot refer to variable declared later (constant)
  63. let (_, errors) = parse_and_resolve(
  64. "contract test {
  65. uint x = y + 102;
  66. uint constant y = 102;
  67. }",
  68. &Target::Substrate,
  69. );
  70. assert_eq!(first_error(errors), "`y' is not declared");
  71. // cannot refer to yourself
  72. let (_, errors) = parse_and_resolve(
  73. "contract test {
  74. uint x = x + 102;
  75. }",
  76. &Target::Substrate,
  77. );
  78. assert_eq!(first_error(errors), "`x' is not declared");
  79. }