Skip to content

Commit

Permalink
Rename variables
Browse files Browse the repository at this point in the history
  • Loading branch information
jeparlefrancais committed Mar 2, 2020
1 parent 66577ad commit 86fb53d
Show file tree
Hide file tree
Showing 24 changed files with 1,119 additions and 39 deletions.
15 changes: 15 additions & 0 deletions .gitlab-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,25 @@ build:
- cargo/
- target/

build-release:
stage: build
extends: .only-mr-and-master
script:
- rustc --version
- cargo --version
- cargo build --release --verbose
artifacts:
expire_in: 1 hour
paths:
- cargo/
- target/

test:
stage: test
extends: .only-mr-and-master
script:
- cargo test --verbose
needs: ['build']

.lua-setup:
before_script:
Expand All @@ -52,3 +66,4 @@ test-lua-projects:
- .lua-setup
script:
- lua ./bin/test-commands.lua
needs: ['build-release']
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "darklua"
version = "0.2.0"
version = "0.2.1"
authors = ["jeparlefrancais <jeparlefrancais21@gmail.com>"]
edition = "2018"
readme = "README.md"
Expand All @@ -22,7 +22,7 @@ path = "src/bin.rs"

[dependencies]
structopt = "0.3.9"
luaparser = { version = "0.1.0", default-features = false }
luaparser = { version = "0.1.1", default-features = false }
serde = "1.0"
json5 = "0.2"

Expand Down
56 changes: 53 additions & 3 deletions RULES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

You can find the available rules and their properties here. The default rule stack is:

```
remove_empty_do
```
- [Remove empty do statements](#remove-empty-do-statements)
- [Rename variables](#rename-variables)

---

## Remove empty do statements
```remove_empty_do```
Expand All @@ -17,3 +18,52 @@ This rule does not have any properties.
rule: 'remove_empty_do',
}
```

---

## Rename variables
```rename_variables```

Rename all declared variables and function parameters.

### Examples
The default rule configuration.
```json5
{
rule: 'rename_variables',
globals: ['$default'],
}
```
The configuration for Roblox Lua.
```json5
{
rule: 'rename_variables',
globals: ['$default', '$roblox'],
}
```
A configuration to avoid all identifiers from the default group and the identifier `a` and `b`.
```json5
{
rule: 'rename_variables',
globals: ['$default', 'a', 'b'],
}
```

### Property
| name | type | default | description |
| --- | --- | --- | --- |
| globals | string array | `['$default']` | a list of identifiers to avoid |

The `globals` property have special values that can be use to group multiple values together. They start with an `$` character.

#### `$default`
The default standard globals in Lua
```
arg, assert, collectgarbage, coroutine, debug, dofile, error, gcinfo, getfenv, getmetatable, io, ipairs, load, loadfile, loadstring, math, module, newproxy, next, os, package, pairs, pcall, print, rawequal, rawget, rawset, require, select, setfenv, setmetatable, string, table, tonumber, tostring, type, unpack, xpcall, _G, _VERSION
```

#### `$roblox`
The globals from Roblox Lua
```
Axes, bit32, BrickColor, CellId, ColorSequence, ColorSequenceKeypoint, Color3, CFrame, DateTime, DebuggerManager, delay, DockWidgetPluginGuiInfo, elapsedTime, Enum, Faces, Instance, LoadLibrary, game, NumberRange, NumberSequence, NumberSequenceKeypoint, PathWaypoint, PhysicalProperties, plugin, PluginDrag, PluginManager, printidentity, Random, Ray, RaycastParams, Rect, Region3, Region3int16, script, settings, shared, stats, spawn, tick, time, TweenInfo, typeof, UDim, UDim2, UserSettings, utf8, Vector2, Vector2int16, Vector3, Vector3int16, version, wait, warn, workspace, ypcall
```
61 changes: 58 additions & 3 deletions bin/test-commands.lua
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
local CONFIG_FILE_NAME = '.darklua.json5'

local function concatCommands(...)
return table.concat({...}, ' && ')
end
Expand Down Expand Up @@ -56,13 +58,52 @@ function Project:test(generatedFolderName)
return run((self.Test:gsub('%$generated', generatedFolderName)))
end

local Json = {}

function Json.fromArray(array)
local content = {}

for i=1, #array do
table.insert(content, Json.from(array[i]))
end

return ('[%s]'):format(table.concat(content, ','))
end

function Json.fromMap(data)
local content = {}

for key, value in pairs(data) do
table.insert(content, ('%s:%s'):format(key, Json.from(value)))
end

return ('{%s}'):format(table.concat(content, ','))
end

function Json.from(data)
local dataType = type(data)

if dataType == 'table' then
if #data ~= 0 then
return Json.fromArray(data)
else
return Json.fromMap(data)
end
elseif dataType == 'string' then
return ('"%s"'):format(data)
end

return tostring(data)
end

local DarkluaTest = {}
local darkluaTestMetatable = {__index = DarkluaTest}

function DarkluaTest.new(name, ...)
function DarkluaTest.new(name, command, config)
return setmetatable({
Name = name,
Command = concatCommands(...),
Command = command,
ConfigurationFile = config and Json.fromMap(config) or '',
}, darkluaTestMetatable)
end

Expand All @@ -75,7 +116,15 @@ function DarkluaTest:execute(project)
:gsub('$input', project.ProcessFolder)
:gsub('$output', output)

verifyRun('cargo run -- ' .. command)
if self.ConfigurationFile:len() > 0 then
local configFile = io.open(CONFIG_FILE_NAME, 'w+')
configFile:write(self.ConfigurationFile)
configFile:close()
end

verifyRun('cargo run --release -- ' .. command)

verifyRun(('rm -f %s'):format(CONFIG_FILE_NAME))

local success, message = project:test(generatedName)

Expand Down Expand Up @@ -142,6 +191,12 @@ local projects = {
local testSuite = {
DarkluaTest.new('minify', 'minify $input $output'),
DarkluaTest.new('default-process', 'process $input $output'),
DarkluaTest.new('rename', 'process $input $output', {
process = {{
rule = 'rename_variables',
globals = {'$default', '$roblox'},
}}
}),
}

local failFast = false
Expand Down
4 changes: 4 additions & 0 deletions src/nodes/expressions/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ impl FunctionExpression {
pub fn mutate_block(&mut self) -> &mut Block {
&mut self.block
}

pub fn mutate_parameters(&mut self) -> &mut Vec<String> {
&mut self.parameters
}
}

impl Default for FunctionExpression {
Expand Down
4 changes: 4 additions & 0 deletions src/nodes/expressions/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ impl IndexExpression {
pub fn mutate_prefix(&mut self) -> &mut Prefix {
&mut self.prefix
}

pub fn mutate_index(&mut self) -> &mut Expression {
&mut self.index
}
}

impl ToLua for IndexExpression {
Expand Down
8 changes: 8 additions & 0 deletions src/nodes/statements/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ impl FunctionName {
pub fn set_name(&mut self, name: String) {
self.name = name;
}

pub fn mutate_identifier(&mut self) -> &mut String {
&mut self.name
}
}

impl ToLua for FunctionName {
Expand Down Expand Up @@ -122,6 +126,10 @@ impl FunctionStatement {
&mut self.name
}

pub fn mutate_parameters(&mut self) -> &mut Vec<String> {
&mut self.parameters
}

pub fn remove_method(&mut self) {
if let Some(method_name) = self.name.remove_method() {
self.name.push_field(method_name);
Expand Down
8 changes: 8 additions & 0 deletions src/nodes/statements/local_assign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ impl LocalAssignStatement {
&self.variables
}

pub fn for_each_assignment<F>(&mut self, mut callback: F)
where F: FnMut(&mut String, Option<&mut Expression>)
{
let mut values = self.values.iter_mut();
self.variables.iter_mut()
.for_each(|variable| callback(variable, values.next()));
}

pub fn mutate_variables(&mut self) -> &mut Vec<String> {
&mut self.variables
}
Expand Down
8 changes: 8 additions & 0 deletions src/nodes/statements/local_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ impl LocalFunctionStatement {
pub fn mutate_block(&mut self) -> &mut Block {
&mut self.block
}

pub fn mutate_parameters(&mut self) -> &mut Vec<String> {
&mut self.parameters
}

pub fn mutate_identifier(&mut self) -> &mut String {
&mut self.identifier
}
}

impl ToLua for LocalFunctionStatement {
Expand Down
4 changes: 4 additions & 0 deletions src/nodes/statements/numeric_for.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ impl NumericForStatement {
&self.identifier
}

pub fn mutate_identifier(&mut self) -> &mut String {
&mut self.identifier
}

pub fn set_identifier<S: Into<String>>(&mut self, identifier: S) {
self.identifier = identifier.into();
}
Expand Down
2 changes: 2 additions & 0 deletions src/process/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
#[cfg(test)]
mod node_counter;
mod node_processor;
mod scope_visitor;
mod visitors;

#[cfg(test)]
pub use node_counter::NodeCounter;
pub use node_processor::NodeProcessor;
pub use scope_visitor::{Scope, ScopeVisitor};
pub use visitors::{DefaultVisitor, NodeVisitor};
Loading

0 comments on commit 86fb53d

Please sign in to comment.