Commit cc56a36d authored by Laurent Le Brun's avatar Laurent Le Brun
Browse files

Code cleanup

Remove dead code
parent 0627e32b
......@@ -12,10 +12,8 @@ let mutable targetOutput = CHeader
let mutable verbose = false
let mutable smoothstepTrick = false
let mutable fieldNames = "xyzw"
let mutable macroThreshold = 10000
let mutable preserveExternals = false
let mutable preserveAllGlobals = false
let generatedMacros = Dictionary<string, int>()
let mutable reorderDeclarations = false
let mutable reorderFunctions = false
let mutable hlsl = false
......@@ -152,7 +150,7 @@ let rec mapInstr env i =
env, env.fInstr res
let mapTopLevel env li =
let env, res = li |> foldList env (fun env tl ->
let _, res = li |> foldList env (fun env tl ->
match tl with
| TLDecl t ->
let env, res = mapDecl env t
......@@ -160,21 +158,3 @@ let mapTopLevel env li =
| Function(fct, body) -> env, Function(fct, snd (mapInstr env body))
| e -> env, e)
res
let countIdent code =
let count = ref 0
let add li = count := !count + List.length li
let mapInstr = function
| Decl (_, li) as e -> add li; e
| ForD((_, li), _, _, _) as e -> add li; e
| e -> e
let mapExpr _ e = e
let mapTL = function
| Function(fct, _) -> incr count; add fct.args
| TLDecl (_, li) -> add li
| _ -> ()
mapTopLevel (mapEnv mapExpr mapInstr) code |> ignore
List.iter mapTL code
!count
......@@ -36,12 +36,12 @@ let printSize code =
let rename code =
Printer.printMode <- Printer.SingleChar
let code, lastIdent = Renamer.renTopLevel code Renamer.Unambiguous
let code = Renamer.renTopLevel code Renamer.Unambiguous
computeFrequencyIdentTable code
Renamer.computeContextTable code
Printer.printMode <- Printer.FromTable
let code, lastIdent = Renamer.renTopLevel code Renamer.Context
let code = Renamer.renTopLevel code Renamer.Context
vprintf "%d identifiers renamed. " Renamer.numberOfUsedIdents
printSize code
code
......@@ -68,13 +68,6 @@ let minify file =
if Ast.noRenaming then code
else rename code
// vprintf "Identifiers renamed. "; printSize code
// let code =
// if !Ast.macroThreshold < 10000 then
// let code, n = Rewriter.injectMacros lastIdent code
// vprintfn "%d macros added." n
// code
// else code
vprintf "Minification of '%s' finished.\n" file
code
......
......@@ -203,7 +203,7 @@ module private ParseImpl =
|>> (function Some s -> "<" + s + ">" | None -> "")
let typeName = pipe2 ident generic (+)
let typeSpec = structSpecifier <|> (typeName |>> Ast.TypeName)
pipe3 qualifier typeSpec generic (fun tyQ name gen -> Ast.makeType name tyQ)
pipe3 qualifier typeSpec generic (fun tyQ name _ -> Ast.makeType name tyQ)
let specifiedType =
if Ast.hlsl then specifiedTypeHLSL else specifiedTypeGLSL
......@@ -314,7 +314,7 @@ module private ParseImpl =
attempt ((declaration .>> ch ';') |>> Ast.Decl)
simpleStatement .>> ch ';'] <?> "instruction"
// eg. "int foo(float a[], out int b) : color"
// e.g. "int foo(float a[], out int b) : color"
let functionHeader =
let void_ = keyword "void" |>> (fun _ -> [])
let argList = void_ <|> (sepBy singleDeclaration (ch ','))
......@@ -344,7 +344,7 @@ module private ParseImpl =
let res = runParserOnString parse () filename content
match res with
| Success(r,_,_) -> r
| Failure(str, exn, _) -> failwithf "Parse error: %s" str
| Failure(str, _, _) -> failwithf "Parse error: %s" str
let runParser = ParseImpl.runParser
......@@ -2,7 +2,7 @@
open Ast
let mutable identTable = [||]
let mutable identTable: string[] = [||]
let out a = sprintf a
// how to print variable names
......@@ -35,19 +35,13 @@ let precedence =
|> List.concat
|> dict
// check if the string is defined by a macro
let (!!) str =
match generatedMacros.TryGetValue str with
| true, s -> identTable.[int s]
| false, _ -> str
let idToS (id: string) =
if id.[0] = '0' then
match printMode with
| FromTable -> !!id // identTable.[int id]
| FromTable -> id
| Nothing -> ""
| SingleChar -> string (char (1000 + int id))
else !!id
else id
let listToS toS sep li =
List.map toS li |> String.concat sep
......@@ -56,14 +50,14 @@ let floatToS f =
let si = if f < 0. then "-" else ""
let test = out "%g" (abs f)
// display "3." instead of "3"
if fst (System.Int32.TryParse test) then !!(out "%g." f)
if fst (System.Int32.TryParse test) then (out "%g." f)
// display ".5" instead of "0.5"
else if test.[0] = '0' then si + !!(test.[1..])
else si + !!test
else if test.[0] = '0' then si + (test.[1..])
else si + test
let rec exprToS exp = exprToSLevel 0 exp
and exprToSLevel level = function
| Int (i, suf) -> !!(out "%d%s" i suf)
| Int (i, suf) -> (out "%d%s" i suf)
| Float (f, suf) -> out "%s%s" (floatToS f) suf
| Var s -> idToS s
| FunCall(f, args) ->
......@@ -127,9 +121,9 @@ and typeSpecToS = function
| TypeStruct(prefix, id, decls) -> structToS prefix id decls
and typeToS (ty: Type) =
let get = Option.fold (fun _ s -> !!s + " ") ""
let get = Option.fold (fun _ s -> s + " ") ""
let typeSpec = typeSpecToS ty.name
out "%s%s" (get ty.typeQ) !!typeSpec
out "%s%s" (get ty.typeQ) typeSpec
and declToS (ty, vars) =
let out1 decl =
......@@ -179,23 +173,23 @@ let rec instrToS' indent = function
| If(cond, th, el) ->
let el = match el with
| None -> ""
| Some el -> out "%s%s%s%s" (nl indent) !!"else" (nl (indent+1)) (instrToS' (indent+1) el |> sp)
| Some el -> out "%s%s%s%s" (nl indent) "else" (nl (indent+1)) (instrToS' (indent+1) el |> sp)
out "if(%s)%s%s" (exprToS cond) (instrToSInd indent th) el
| ForD(init, cond, inc, body) ->
let cond = defaultArg (Option.map exprToS cond) ""
let inc = defaultArg (Option.map exprToS inc) ""
out "%s(%s;%s;%s)%s" !!"for" (declToS init) cond inc (instrToSInd indent body)
out "%s(%s;%s;%s)%s" "for" (declToS init) cond inc (instrToSInd indent body)
| ForE(init, cond, inc, body) ->
let cond = defaultArg (Option.map exprToS cond) ""
let inc = defaultArg (Option.map exprToS inc) ""
let init = defaultArg (Option.map exprToS init) ""
out "%s(%s;%s;%s)%s" !!"for" init cond inc (instrToSInd indent body)
out "%s(%s;%s;%s)%s" "for" init cond inc (instrToSInd indent body)
| While(cond, body) ->
out "%s(%s)%s" !!"while" (exprToS cond) (instrToSInd indent body)
out "%s(%s)%s" "while" (exprToS cond) (instrToSInd indent body)
| DoWhile(cond, body) ->
out "%s%s%s(%s)" !!"do" !!"while" (exprToS cond |> sp) (instrToS indent body)
| Keyword(k, None) -> out "%s;" !!k
| Keyword(k, Some exp) -> out "%s%s;" !!k (exprToS exp |> sp)
out "%s%s%s(%s)" "do" "while" (exprToS cond |> sp) (instrToS indent body)
| Keyword(k, None) -> out "%s;" k
| Keyword(k, Some exp) -> out "%s%s;" k (exprToS exp |> sp)
| Verbatim s ->
// add a space at end when it seems to be needed
let s = if System.Char.IsLetterOrDigit s.[s.Length - 1] then s + " " else s
......
......@@ -50,12 +50,12 @@ let chooseIdent ident candidates =
for word in candidates do
let letter = (word : string).[0] // FIXME: use both first and last letter to compute stats
let mutable score = 0
for c, occ in prevs do
for c, _ in prevs do
match contextTable.TryFind (c, letter) with
| None -> ()
| Some occ2 -> score <- score + occ2 // * occ
for c, occ in nexts do
for c, _ in nexts do
match contextTable.TryFind (letter, c) with
| None -> ()
| Some occ2 -> score <- score + occ2 // * occ
......@@ -108,20 +108,18 @@ let alwaysNewName env id =
let optimizeFrequency env id =
match env.reusable with
|[] -> // create a new variable
| [] -> // create a new variable
let newName = sprintf "%04d" env.max
let env = {env with map = Map.add id newName env.map; max = env.max + 1}
numberOfUsedIdents <- max numberOfUsedIdents env.max
env, newName
|e::l -> // reuse a variable name
| e::l -> // reuse a variable name
{env with map = Map.add id e env.map; reusable = l}, e
// FIXME: handle 2-letter names
let optimizeContext env id =
let cid = char (1000 + int id)
let l2 = env.reusable
// |> Seq.choose (fun s -> if s.Length = 1 then Some s.[0] else None)
let newName = chooseIdent cid l2
let newName = chooseIdent cid env.reusable
let l = env.reusable |> List.filter (fun x -> x.[0] <> newName.[0])
{env with map = Map.add id newName env.map; reusable = l}, newName
......@@ -225,16 +223,14 @@ let rec renInstr env =
| Decl d ->
let env, res = renDecl false env d
env, Decl res
| Block b as i ->
//let env = garbage env i
| Block b ->
let _, res = renList env renInstr b
env, Block res
| If(cond, th, el) ->
let _, th = renInstr env th
let el = Option.map (fun x -> snd (renInstr env x)) el
env, If(renExpr env cond, th, el)
| ForD(init, cond, inc, body) as loop ->
//let newEnv = garbage env loop
| ForD(init, cond, inc, body) ->
let newEnv, init = renDecl false env init
let _, body = renInstr newEnv body
let cond = Option.map (renExpr newEnv) cond
......@@ -266,7 +262,7 @@ let rec renTopLevelBody env = function
| Function(fct, body) ->
let env = garbage env body
let env, args = renList env (renDecl false) fct.args
let env, body = renInstr env body
let _env, body = renInstr env body
Function({fct with args=args}, body)
| e -> e
......@@ -290,4 +286,4 @@ let rec renTopLevel li mode =
let env, li = renList env renTopLevelName li
// Then, rename local values
List.map (renTopLevelBody env) li, numberOfUsedIdents-1
List.map (renTopLevelBody env) li
......@@ -132,7 +132,7 @@ let rec expr env = function
| Var s as e when hasInlinePrefix s ->
match Map.tryFind s env.vars with
| Some (ty, size, Some init) -> init
| Some (_, _, Some init) -> init
| _ -> e
| e -> e
......@@ -171,7 +171,9 @@ let instr = function
// Try to remove blocks by using the comma operator
let returnExp = b |> Seq.tryPick (function Keyword("return", e) -> e | _ -> None)
let canOptimize = b |> List.forall (function
| Expr _ -> true | Keyword("return", Some e) -> true | _ -> false)
| Expr _ -> true
| Keyword("return", Some _) -> true
| _ -> false)
if not Ast.noSequence && canOptimize then
let li = List.choose (function Expr e -> Some e | _ -> None) b
......@@ -187,9 +189,9 @@ let instr = function
| Decl (ty, li) -> Decl (rwType ty, declsNotToInline li)
| ForD((ty, d), cond, inc, body) -> ForD((rwType ty, declsNotToInline d), cond, inc, body)
// FIXME: properly handle booleans
| If(Var "true", e1, e2) -> e1
| If(Var "false", e1, Some e2) -> e2
| If(Var "false", e1, None) -> Block []
| If(Var "true", e1, _) -> e1
| If(Var "false", _, Some e2) -> e2
| If(Var "false", _, None) -> Block []
| If(c, b, Some (Block [])) -> If(c, b, None)
| Verbatim s -> Verbatim (stripSpaces s)
| e -> e
......@@ -212,65 +214,6 @@ let apply li =
)
|> squeezeTLDeclarations
(* ** Macro creation ** *)
let macroCount = Dictionary()
let addWord str =
if str <> "" then
match macroCount.TryGetValue str with
| true, n -> macroCount.Remove str |> ignore; macroCount.Add(str, (n + 1))
| false, _ -> macroCount.Add(str, 1)
let macroExpr _ expr =
match expr with
| Var s when System.Char.IsLetter s.[0] -> addWord s
| Int _ -> addWord (Printer.exprToS expr)
| Float _ -> addWord (Printer.exprToS expr)
| _ -> ()
expr
let macroTy (ty:Type) =
match ty.name with TypeName s -> addWord s | TypeStruct _ -> () // FIXME
addWord (defaultArg ty.typeQ "")
let macroInstr expr =
match expr with
| Decl (ty, _) -> macroTy ty
| If(_, _, el) -> addWord "if"; if el <> None then addWord "else"
| ForD((ty, _), _, _, _) -> macroTy ty; addWord "for"
| ForE(_, _, _, _) -> addWord "for"
| While(_, _) -> addWord "while"
| DoWhile(_, _) -> addWord "do"; addWord "while"
| Keyword(k, _) -> addWord k
| _ -> ()
expr
let macroTL = function
| Function(fct, _) ->
List.iter (fst >> macroTy) fct.args
macroTy fct.retType
| TLDecl (ty, _) -> macroTy ty
| _ -> ()
let injectMacros numberOfIdent code =
macroCount.Clear()
generatedMacros.Clear()
List.iter macroTL code
mapTopLevel (mapEnv macroExpr macroInstr) code |> ignore
let macroLen = "#define \n".Length
let mutable name = numberOfIdent
for i in macroCount do
let oldLen = i.Value * i.Key.Length
// check if we still have 1-char names available
let newIdentSize = if name > 26 * 2 then 2 else 1
let newLen = macroLen + i.Key.Length + newIdentSize * i.Value
//printfn "%s: %d vs %d" i.Key oldLen newLen
if oldLen - newLen >= macroThreshold then
name <- name + 1
generatedMacros.Add(i.Key, name)
let macros = [for i in generatedMacros ->
TLVerbatim(sprintf "define %s %s" Printer.identTable.[i.Value] i.Key)]
macros @ code, name - numberOfIdent
(* Reorder functions because of forward declarations *)
......
void f() {
int x = 5;
int y = 7;
if (1) {
return 2;
} else {;}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment