Skip to content

Commit

Permalink
[ #363 #287 ] fixed for Ocaml: cons, sanitization of keywords
Browse files Browse the repository at this point in the history
  • Loading branch information
andreasabel committed May 18, 2021
1 parent a3b50a9 commit d67f07e
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 5 deletions.
9 changes: 5 additions & 4 deletions source/src/BNFC/Backend/OCaml/CFtoOCamlAbs.hs
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,15 @@ definedRules :: CF -> [String]
definedRules cf = map mkDef $ definitions cf
where
mkDef (Define f args e t) =
"let " ++ funName f ++ " " ++ mkTuple (map fst args) ++ " = " ++ ocamlExp False e
"let " ++ sanitizeOcaml (funName f) ++ " " ++ mkTuple (map fst args) ++ " = " ++ ocamlExp False e

ocamlExp :: Bool -> Exp -> String
ocamlExp p = \case
Var s -> s
App s _ [] -> s
App s _ [e] -> parensIf p $ s ++ ' ' : ocamlExp True e
App s _ es -> parensIf p $ s ++ ' ' : mkTuple (map (ocamlExp False) es)
App "(:)" _ [e1, e2] -> parensIf p $ unwords [ ocamlExp True e1, "::", ocamlExp False e2 ]
App s _ [] -> sanitizeOcaml s
App s _ [e] -> parensIf p $ sanitizeOcaml s ++ ' ' : ocamlExp True e
App s _ es -> parensIf p $ sanitizeOcaml s ++ ' ' : mkTuple (map (ocamlExp False) es)
LitInt i -> show i
LitDouble d -> show d
LitChar c -> "\'" ++ c : "\'"
Expand Down
2 changes: 1 addition & 1 deletion source/src/BNFC/Backend/OCaml/CFtoOCamlYacc.hs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ generateAction _ f ms = (if isCoercion f then "" else f') +++ mkTuple ms
f' = case funName f of -- ocaml cons is somehow not a standard infix oper, right?
"(:[])" -> "(fun x -> [x])"
"(:)" -> "(fun (x,xs) -> x::xs)"
x -> x
x -> sanitizeOcaml x


generatePatterns :: (String -> String) -> Rule -> (Pattern,[MetaVar])
Expand Down
6 changes: 6 additions & 0 deletions source/src/BNFC/Backend/OCaml/OCamlUtil.hs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ reservedOCaml = [
"true","try","type","val","virtual","when",
"while","with"]

-- | Avoid clashes with keywords.
sanitizeOcaml :: String -> String
sanitizeOcaml s
| s `elem` reservedOCaml = s ++ "_"
| otherwise = s

-- | Keywords of @ocamllex@.
reservedOCamlLex :: [String]
reservedOCamlLex =
Expand Down

0 comments on commit d67f07e

Please sign in to comment.