rubish-gem 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. checksums.yaml +7 -0
  2. data/.dockerignore +23 -0
  3. data/Dockerfile +54 -0
  4. data/LICENSE.txt +21 -0
  5. data/README.md +39 -0
  6. data/Rakefile +12 -0
  7. data/lib/rubish/arithmetic.rb +140 -0
  8. data/lib/rubish/ast.rb +168 -0
  9. data/lib/rubish/builtins/arithmetic.rb +129 -0
  10. data/lib/rubish/builtins/bind_readline.rb +834 -0
  11. data/lib/rubish/builtins/directory_stack.rb +182 -0
  12. data/lib/rubish/builtins/echo_printf.rb +510 -0
  13. data/lib/rubish/builtins/hash_directories.rb +260 -0
  14. data/lib/rubish/builtins/read.rb +299 -0
  15. data/lib/rubish/builtins/trap.rb +324 -0
  16. data/lib/rubish/codegen.rb +1273 -0
  17. data/lib/rubish/completion.rb +840 -0
  18. data/lib/rubish/completions/bash_helpers.rb +530 -0
  19. data/lib/rubish/completions/git.rb +431 -0
  20. data/lib/rubish/completions/help_parser.rb +453 -0
  21. data/lib/rubish/completions/ssh.rb +114 -0
  22. data/lib/rubish/config.rb +267 -0
  23. data/lib/rubish/data/builtin_help.rb +716 -0
  24. data/lib/rubish/data/completion_data.rb +53 -0
  25. data/lib/rubish/data/readline_config.rb +47 -0
  26. data/lib/rubish/data/shell_options.rb +251 -0
  27. data/lib/rubish/data_define.rb +65 -0
  28. data/lib/rubish/execution_context.rb +1124 -0
  29. data/lib/rubish/expansion.rb +988 -0
  30. data/lib/rubish/history.rb +663 -0
  31. data/lib/rubish/lazy_loader.rb +127 -0
  32. data/lib/rubish/lexer.rb +1194 -0
  33. data/lib/rubish/parser.rb +1167 -0
  34. data/lib/rubish/prompt.rb +766 -0
  35. data/lib/rubish/repl.rb +2267 -0
  36. data/lib/rubish/runtime/builtins.rb +7222 -0
  37. data/lib/rubish/runtime/command.rb +1153 -0
  38. data/lib/rubish/runtime/job.rb +153 -0
  39. data/lib/rubish/runtime.rb +1169 -0
  40. data/lib/rubish/shell_state.rb +241 -0
  41. data/lib/rubish/startup_profiler.rb +67 -0
  42. data/lib/rubish/version.rb +5 -0
  43. data/lib/rubish.rb +60 -0
  44. data/sig/rubish.rbs +4 -0
  45. metadata +85 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0be5ff112eea53f1d1242f580cfa73a0230d8cecb63b48136df382abe6f2b1eb
4
+ data.tar.gz: a028f5857b4af3706d449bb888ff7b9fea93f367d91150cb395662c5e07b854b
5
+ SHA512:
6
+ metadata.gz: 1ce7db2b865fb471abfa4fe0b8ffe6e6d5f6ce03651fd93d7512fc5106e340d37e0c41fa2b22344e7baa9dbef84dfdeb46c617fac0c5db7c5d3e3f3def7f0b4c
7
+ data.tar.gz: 6a731ffce72bca0c93f08c1a601c8e58839020c37c4ed5368eb5c0eef3de7ef0b11c21d0535241244aace1c253c70d9f714d1a111b15e6796bc453b94d6a9bb1
data/.dockerignore ADDED
@@ -0,0 +1,23 @@
1
+ # Git
2
+ .git
3
+ .gitignore
4
+
5
+ # Docker
6
+ Dockerfile
7
+ .dockerignore
8
+
9
+ # Editor/IDE
10
+ *.swp
11
+ *.swo
12
+ *~
13
+
14
+ # OS
15
+ .DS_Store
16
+
17
+ # Ruby
18
+ .bundle
19
+ vendor/bundle
20
+
21
+ # Test artifacts
22
+ coverage
23
+ tmp
data/Dockerfile ADDED
@@ -0,0 +1,54 @@
1
+ # Dockerfile for running rubish tests in a clean environment
2
+ # This avoids loading developer's local rc files during tests
3
+
4
+ FROM ruby:4.0-slim
5
+
6
+ # Install build dependencies
7
+ RUN apt-get update && apt-get install -y --no-install-recommends \
8
+ build-essential \
9
+ git \
10
+ && rm -rf /var/lib/apt/lists/*
11
+
12
+ # Verify Ruby version
13
+ RUN ruby -v
14
+
15
+ # Create a test user with a clean home directory and multiple groups
16
+ RUN groupadd testgroup1 && \
17
+ groupadd testgroup2 && \
18
+ useradd -m -s /bin/bash -G testgroup1,testgroup2 testuser
19
+
20
+ # Set working directory
21
+ WORKDIR /app
22
+
23
+ # Copy Gemfile first for layer caching
24
+ COPY Gemfile Gemfile.lock* ./
25
+
26
+ # Install dependencies
27
+ RUN bundle install
28
+
29
+ # Copy the rest of the application
30
+ COPY . .
31
+
32
+ # Ensure clean home directory (no rc files)
33
+ RUN rm -f /home/testuser/.bashrc \
34
+ /home/testuser/.bash_profile \
35
+ /home/testuser/.profile \
36
+ /home/testuser/.bash_logout \
37
+ /root/.bashrc \
38
+ /root/.bash_profile \
39
+ /root/.profile \
40
+ && mkdir -p /home/testuser \
41
+ && chown -R testuser:testuser /home/testuser /app
42
+
43
+ # Switch to test user
44
+ USER testuser
45
+ ENV HOME=/home/testuser
46
+
47
+ # Ensure no rc files exist (don't set XDG_CONFIG_HOME - let tests control it)
48
+ RUN rm -rf /home/testuser/.config/rubish \
49
+ /home/testuser/.rubishrc \
50
+ /home/testuser/.rubish_profile \
51
+ /home/testuser/.rubish_logout
52
+
53
+ # Run tests
54
+ CMD ["bundle", "exec", "rake", "test"]
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Akira Matsuda
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # Rubish
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/rubish`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ ```bash
14
+ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
15
+ ```
16
+
17
+ If bundler is not being used to manage dependencies, install the gem by executing:
18
+
19
+ ```bash
20
+ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/amatsuda/rubish.
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rake/testtask'
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << 'test'
8
+ t.libs << 'lib'
9
+ t.test_files = FileList['test/**/*_test.rb']
10
+ end
11
+
12
+ task default: :test
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubish
4
+ # Arithmetic evaluation helpers for the shell REPL
5
+ # Handles $(( )), (( )), and arithmetic for loops
6
+ module Arithmetic
7
+ def eval_arithmetic_expr(expr)
8
+ # Handle comma-separated expressions (evaluate all, return last)
9
+ # Be careful not to split inside parentheses
10
+ expressions = split_arithmetic_expressions(expr)
11
+ result = 0
12
+
13
+ expressions.each do |e|
14
+ e = e.strip
15
+ next if e.empty?
16
+
17
+ result = eval_single_arithmetic(e)
18
+ end
19
+
20
+ result
21
+ end
22
+
23
+ def split_arithmetic_expressions(expr)
24
+ # Split by comma, but not inside parentheses
25
+ result = []
26
+ current = +''
27
+ depth = 0
28
+
29
+ expr.each_char do |c|
30
+ case c
31
+ when '('
32
+ depth += 1
33
+ current << c
34
+ when ')'
35
+ depth -= 1
36
+ current << c
37
+ when ','
38
+ if depth == 0
39
+ result << current
40
+ current = +''
41
+ else
42
+ current << c
43
+ end
44
+ else
45
+ current << c
46
+ end
47
+ end
48
+
49
+ result << current unless current.empty?
50
+ result
51
+ end
52
+
53
+ def eval_single_arithmetic(expr)
54
+ # Handle pre-increment/decrement: ++var, --var
55
+ if expr =~ /\A\+\+([a-zA-Z_][a-zA-Z0-9_]*)\z/
56
+ var = $1
57
+ val = (Builtins.get_var(var) || '0').to_i + 1
58
+ Builtins.set_var(var, val.to_s)
59
+ return val
60
+ end
61
+
62
+ if expr =~ /\A--([a-zA-Z_][a-zA-Z0-9_]*)\z/
63
+ var = $1
64
+ val = (Builtins.get_var(var) || '0').to_i - 1
65
+ Builtins.set_var(var, val.to_s)
66
+ return val
67
+ end
68
+
69
+ # Handle post-increment/decrement: var++, var--
70
+ if expr =~ /\A([a-zA-Z_][a-zA-Z0-9_]*)\+\+\z/
71
+ var = $1
72
+ old_val = (Builtins.get_var(var) || '0').to_i
73
+ Builtins.set_var(var, (old_val + 1).to_s)
74
+ return old_val
75
+ end
76
+
77
+ if expr =~ /\A([a-zA-Z_][a-zA-Z0-9_]*)--\z/
78
+ var = $1
79
+ old_val = (Builtins.get_var(var) || '0').to_i
80
+ Builtins.set_var(var, (old_val - 1).to_s)
81
+ return old_val
82
+ end
83
+
84
+ # Handle compound assignments: var+=, var-=, var*=, var/=, var%=, var<<=, var>>=, var&=, var|=, var^=
85
+ if expr =~ /\A([a-zA-Z_][a-zA-Z0-9_]*)\s*(\+|-|\*|\/|%|<<|>>|&|\||\^)=\s*(.+)\z/
86
+ var, op, rhs = $1, $2, $3
87
+ lhs_val = (Builtins.get_var(var) || '0').to_i
88
+ rhs_val = eval_single_arithmetic(rhs)
89
+ result = case op
90
+ when '+' then lhs_val + rhs_val
91
+ when '-' then lhs_val - rhs_val
92
+ when '*' then lhs_val * rhs_val
93
+ when '/' then rhs_val != 0 ? lhs_val / rhs_val : 0
94
+ when '%' then rhs_val != 0 ? lhs_val % rhs_val : 0
95
+ when '<<' then lhs_val << rhs_val
96
+ when '>>' then lhs_val >> rhs_val
97
+ when '&' then lhs_val & rhs_val
98
+ when '|' then lhs_val | rhs_val
99
+ when '^' then lhs_val ^ rhs_val
100
+ end
101
+ Builtins.set_var(var, result.to_s)
102
+ return result
103
+ end
104
+
105
+ # Handle simple assignment: var=expr (but not == comparison)
106
+ if expr =~ /\A([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(?!=)(.+)\z/
107
+ var, rhs = $1, $2
108
+ result = eval_single_arithmetic(rhs)
109
+ Builtins.set_var(var, result.to_s)
110
+ return result
111
+ end
112
+
113
+ # Regular arithmetic expression - evaluate directly to handle booleans
114
+ # Expand variables first
115
+ expanded = expr.gsub(/\$\{([^}]+)\}|\$(\d+)|\$([a-zA-Z_][a-zA-Z0-9_]*)|([a-zA-Z_][a-zA-Z0-9_]*)/) do |match|
116
+ if $2 # Positional parameter like $1, $2
117
+ n = $2.to_i
118
+ (@positional_params[n - 1] || '0')
119
+ elsif (var_name = $1 || $3 || $4)
120
+ get_special_var(var_name) || Builtins.get_var(var_name) || '0'
121
+ else
122
+ match
123
+ end
124
+ end
125
+
126
+ begin
127
+ result = Kernel.eval(expanded)
128
+ # Handle boolean results (comparison operators return true/false in Ruby)
129
+ case result
130
+ when true then 1
131
+ when false then 0
132
+ when Numeric then result.to_i
133
+ else result.to_s.to_i
134
+ end
135
+ rescue StandardError
136
+ 0
137
+ end
138
+ end
139
+ end
140
+ end
data/lib/rubish/ast.rb ADDED
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubish
4
+ module AST
5
+ # Single command: ls -la
6
+ # env: prefix environment variables (e.g., FOO=bar cmd)
7
+ Command = Data.define(:name, :args, :block, :env) do
8
+ def initialize(name:, args: [], block: nil, env: [])
9
+ super
10
+ end
11
+ end
12
+
13
+ # Pipeline: cmd1 | cmd2 | cmd3
14
+ # pipe_types: array of :pipe or :pipe_both (for |&) indicating connection type between commands
15
+ # If nil or empty, all pipes are regular pipes
16
+ Pipeline = Data.define(:commands, :pipe_types) do
17
+ def initialize(commands:, pipe_types: nil)
18
+ super
19
+ end
20
+ end
21
+
22
+ # Negation: ! pipeline - negates exit status of pipeline
23
+ Negation = Data.define(:command)
24
+
25
+ # Command list: cmd1 ; cmd2
26
+ List = Data.define(:commands)
27
+
28
+ # Redirect: cmd > file
29
+ Redirect = Data.define(:command, :operator, :target)
30
+
31
+ # VarnameRedirect: cmd {fd}>file - allocates FD to variable
32
+ # varname: the variable name to store the allocated FD
33
+ # operator: the redirection operator (>, >>, <, >&, <&)
34
+ # target: the file or FD number
35
+ VarnameRedirect = Data.define(:command, :varname, :operator, :target)
36
+
37
+ # Background: cmd &
38
+ Background = Data.define(:command)
39
+
40
+ # Conditional: cmd1 && cmd2
41
+ And = Data.define(:left, :right)
42
+
43
+ # Conditional: cmd1 || cmd2
44
+ Or = Data.define(:left, :right)
45
+
46
+ # Ruby literals as arguments
47
+ ArrayLiteral = Data.define(:value) # [1, 2, 3]
48
+ RegexpLiteral = Data.define(:value) # /pattern/
49
+
50
+ # Process substitution: <(cmd) or >(cmd)
51
+ # direction: :in for <(cmd), :out for >(cmd)
52
+ ProcessSubstitution = Data.define(:command, :direction)
53
+
54
+ # Ruby block condition: { ruby_expression }
55
+ # Used in if/while/until with Ruby expression as condition
56
+ # Shell variables are bound as Ruby locals (VAR -> var)
57
+ RubyCondition = Data.define(:expression)
58
+
59
+ # If statement: if cond; then body; elif cond; then body; else body; fi
60
+ # branches is array of [condition, body] pairs, else_body is optional
61
+ If = Data.define(:branches, :else_body) do
62
+ def initialize(branches:, else_body: nil)
63
+ super
64
+ end
65
+ end
66
+
67
+ # Unless statement (Ruby-style): unless cond ... else ... end
68
+ # Executes body when condition is false (opposite of if)
69
+ Unless = Data.define(:condition, :body, :else_body) do
70
+ def initialize(condition:, body:, else_body: nil)
71
+ super
72
+ end
73
+ end
74
+
75
+ # While loop: while cond; do body; done
76
+ While = Data.define(:condition, :body)
77
+
78
+ # Until loop: until cond; do body; done (loops while condition is false)
79
+ Until = Data.define(:condition, :body)
80
+
81
+ # For loop: for var in items; do body; done
82
+ For = Data.define(:variable, :items, :body)
83
+
84
+ # C-style arithmetic for loop: for ((init; cond; update)); do body; done
85
+ ArithFor = Data.define(:init, :condition, :update, :body)
86
+
87
+ # Select loop: select var in items; do body; done
88
+ Select = Data.define(:variable, :items, :body)
89
+
90
+ # Function definition: function name { body } or name() { body } or def name(params); body; end
91
+ # params is an optional array of parameter names for Ruby-style def with arguments
92
+ Function = Data.define(:name, :body, :params)
93
+
94
+ # Case statement: case word in pattern1) body ;; pattern2|pattern3) body ;; esac
95
+ # word: the value to match against patterns (string or RubyCondition)
96
+ # - string: shell variable/word to match (e.g., "$VAR")
97
+ # - RubyCondition: Ruby expression whose result is matched (e.g., { var.downcase })
98
+ # branches is array of [patterns, body, terminator] where:
99
+ # - patterns is array of pattern strings
100
+ # - body is the AST for the branch body
101
+ # - terminator is :double_semi (;;), :fall (;&), :cont (;;&), or nil (last branch)
102
+ Case = Data.define(:word, :branches)
103
+
104
+ # Subshell: (commands) - runs commands in a child process
105
+ Subshell = Data.define(:body)
106
+
107
+ # Heredoc: cmd <<EOF ... EOF - provides multi-line input to command
108
+ # delimiter: the terminating word (e.g., "EOF")
109
+ # content: the heredoc content (set later when lines are collected)
110
+ # expand: true if variables should be expanded
111
+ # strip_tabs: true for <<- (allows indented delimiter)
112
+ Heredoc = Data.define(:command, :delimiter, :content, :expand, :strip_tabs) do
113
+ def initialize(command:, delimiter:, content: nil, expand: true, strip_tabs: false)
114
+ super
115
+ end
116
+
117
+ def with_content(new_content)
118
+ Heredoc.new(command: command, delimiter: delimiter, content: new_content, expand: expand, strip_tabs: strip_tabs)
119
+ end
120
+ end
121
+
122
+ # Herestring: cmd <<< "string" - provides single-line string as stdin
123
+ Herestring = Data.define(:command, :string)
124
+
125
+ # Coproc: coproc [NAME] command - runs command as coprocess with bidirectional pipes
126
+ # name: the coprocess name (defaults to "COPROC")
127
+ # command: the command to run
128
+ Coproc = Data.define(:name, :command) do
129
+ def initialize(name: 'COPROC', command:)
130
+ super
131
+ end
132
+ end
133
+
134
+ # Time: time [-p] pipeline - measure execution time of a command
135
+ # posix_format: true if -p flag is used (POSIX format output)
136
+ # command: the command/pipeline to time
137
+ Time = Data.define(:command, :posix_format) do
138
+ def initialize(command:, posix_format: false)
139
+ super
140
+ end
141
+ end
142
+
143
+ # ConditionalExpr: [[ expression ]] - extended test command
144
+ # expression: array of tokens/strings representing the expression
145
+ # Supports: string comparison (==, !=, <, >), pattern matching, regex (=~),
146
+ # file tests (-f, -d, -e, etc.), logical operators (&&, ||, !)
147
+ ConditionalExpr = Data.define(:expression)
148
+
149
+ # ArithmeticCommand: (( expression )) - arithmetic evaluation command
150
+ # expression: the arithmetic expression string
151
+ # Returns exit status 0 if result is non-zero, 1 if result is zero
152
+ ArithmeticCommand = Data.define(:expression)
153
+
154
+ # ArrayAssign: VAR=(a b c) or VAR+=(d e) - array assignment
155
+ # var: the variable name with = or += (e.g., "arr=" or "arr+=")
156
+ # elements: array of element strings
157
+ ArrayAssign = Data.define(:var, :elements)
158
+
159
+ # RubyCode: raw Ruby code for prompt functions
160
+ # code: the Ruby code string to be evaluated
161
+ RubyCode = Data.define(:code)
162
+
163
+ # LazyLoad: lazy_load { commands } - run commands in background thread
164
+ # body: the shell commands to execute in background
165
+ # The commands' output (if eval "$(...)") is captured and applied to main thread
166
+ LazyLoad = Data.define(:body)
167
+ end
168
+ end
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubish
4
+ module Builtins
5
+ def let(args)
6
+ # let expression [expression ...]
7
+ # Evaluates arithmetic expressions
8
+ # Returns 0 (true) if last expression is non-zero, 1 (false) if zero
9
+
10
+ if args.empty?
11
+ puts 'let: usage: let expression [expression ...]'
12
+ return false
13
+ end
14
+
15
+ last_result = 0
16
+
17
+ args.each do |expr|
18
+ last_result = evaluate_arithmetic(expr)
19
+ end
20
+
21
+ # Return true if last result is non-zero (shell convention)
22
+ last_result != 0
23
+ end
24
+
25
+ def evaluate_arithmetic(expr)
26
+ # Handle assignment operators (but not ==, !=, <=, >=)
27
+ if expr =~ /\A([a-zA-Z_][a-zA-Z0-9_]*)\s*([\+\-\*\/%]?=)(?!=)\s*(.+)\z/
28
+ var_name = $1
29
+ operator = $2
30
+ value_expr = $3
31
+
32
+ # Check readonly
33
+ if readonly?(var_name)
34
+ puts "let: #{var_name}: readonly variable"
35
+ return 0
36
+ end
37
+
38
+ # Evaluate the right side
39
+ value = evaluate_arithmetic_expr(value_expr)
40
+
41
+ if operator == '='
42
+ # Simple assignment
43
+ ENV[var_name] = value.to_s
44
+ else
45
+ # Compound assignment (+=, -=, *=, /=, %=)
46
+ current = (ENV[var_name] || '0').to_i
47
+ case operator
48
+ when '+='
49
+ ENV[var_name] = (current + value).to_s
50
+ when '-='
51
+ ENV[var_name] = (current - value).to_s
52
+ when '*='
53
+ ENV[var_name] = (current * value).to_s
54
+ when '/='
55
+ ENV[var_name] = (value.zero? ? 0 : current / value).to_s
56
+ when '%='
57
+ ENV[var_name] = (value.zero? ? 0 : current % value).to_s
58
+ end
59
+ end
60
+
61
+ return ENV[var_name].to_i
62
+ end
63
+
64
+ # Handle increment/decrement operators
65
+ result = apply_increment_decrement(expr)
66
+ return result unless result.nil?
67
+
68
+ # Just evaluate the expression
69
+ evaluate_arithmetic_expr(expr)
70
+ end
71
+
72
+ def apply_increment_decrement(expr)
73
+ # Pre-increment/decrement: ++var, --var
74
+ if expr =~ /\A(\+\+|--)([a-zA-Z_][a-zA-Z0-9_]*)\z/
75
+ op, var_name = $1, $2
76
+ return 0 if readonly?(var_name)
77
+ val = (ENV[var_name] || '0').to_i + (op == '++' ? 1 : -1)
78
+ ENV[var_name] = val.to_s
79
+ return val
80
+ end
81
+
82
+ # Post-increment/decrement: var++, var--
83
+ if expr =~ /\A([a-zA-Z_][a-zA-Z0-9_]*)(\+\+|--)\z/
84
+ var_name, op = $1, $2
85
+ return 0 if readonly?(var_name)
86
+ old_val = (ENV[var_name] || '0').to_i
87
+ ENV[var_name] = (old_val + (op == '++' ? 1 : -1)).to_s
88
+ return old_val
89
+ end
90
+
91
+ nil
92
+ end
93
+
94
+ def evaluate_arithmetic_expr(expr)
95
+ # Replace variable references with their values
96
+ # Handle $VAR, ${VAR}, and bare variable names
97
+ expanded = expr.gsub(/\$\{([^}]+)\}|\$([a-zA-Z_][a-zA-Z0-9_]*)|([a-zA-Z_][a-zA-Z0-9_]*)/) do |match|
98
+ if $1
99
+ # ${VAR} form
100
+ (ENV[$1] || '0')
101
+ elsif $2
102
+ # $VAR form
103
+ (ENV[$2] || '0')
104
+ elsif $3
105
+ # Plain variable name - in arithmetic context, unset vars default to 0
106
+ (ENV[$3] || '0')
107
+ else
108
+ match
109
+ end
110
+ end
111
+
112
+ # Handle logical operators
113
+ expanded = expanded.gsub('&&', ' && ')
114
+ expanded = expanded.gsub('||', ' || ')
115
+ expanded = expanded.gsub(/!(?!=)/, ' !')
116
+
117
+ # Handle ternary operator
118
+ expanded = expanded.gsub('?', ' ? ').gsub(':', ' : ')
119
+
120
+ # Evaluate safely
121
+ begin
122
+ result = Kernel.eval(expanded)
123
+ result.is_a?(Integer) ? result : (result ? 1 : 0)
124
+ rescue StandardError
125
+ 0
126
+ end
127
+ end
128
+ end
129
+ end