Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[hcl mode] Add an HCL mode. #5347

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
257 changes: 257 additions & 0 deletions mode/hcl/hcl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
/**
* @license
* Copyright 2018 Google LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @fileoverview Codemirror 2 mode for HCL files.
* @author octo@google.com (Florian Forster)
*/

(function() {
/**
* Keywords specific to Terraform configurations.
*
* @dict
*/
var terraformKeywords = {
'atlas': true,
'backend': true,
'data': true,
'locals': true,
'module': true,
'output': true,
'provider': true,
'resource': true,
'terraform': true,
'variable': true,
};

/**
* HCL atoms
*
* @dict
*/
var hclAtoms = {
'true': true,
'false': true,
};

/**
* HCL configuration.
*
* @struct
* @extends {CodeMirror.ModeConfig}
*/
var hclConfig = {
name: 'clike',
};

/**
* Terraform configuration.
*
* @struct
* @extends {CodeMirror.ModeConfig}
*/
var terraformConfig = {
name: 'clike',
keywords: terraformKeywords,
};

CodeMirror.defineMode(
'hcl',

/**
* @param {!CodeMirror.EditorConfig} config
* @param {?CodeMirror.ModeConfig} parserConfig
* @return {!CodeMirror.Mode}
*/
function(config, parserConfig) {
/**
* Consumes a quoted string. Quoted strings may span multiple lines and
* intrast to clike's string tokenizer no backslash is required at the end
* of the line.
* @param {!CodeMirror.InputStream} stream Codemirror input stream.
* @param {!Object} state HCL state object.
* @return {string} 'string' token type.
*/
function stringTokenizer(stream, state) {
var escaped = false;
var next;
while ((next = stream.next()) != null) {
if (next == '"' && !escaped) {
state.tokenize = null;
break;
}
escaped = !escaped && next == '\\';
}
return 'string';
}

/**
* Creates a tokenizer that reads a heredoc string until the given
* delimiter is encountered.
* @param {string} delim heredoc delimiter.
* @return {function(!CodeMirror.InputStream,!Object):string} tokenizer
*/
function heredocTokenizerFactory(delim) {
return function(stream, state) {
stream.eatSpace();
if (stream.match(delim, true, false) && stream.eol()) {
state.tokenize = null;
return 'string';
}

stream.skipToEnd();
return 'string';
};
}

/**
* Consume a (multi-line) heredoc literal and emit the 'string' token
* type. This function assumes that a '<' character has already been
* consumed.
* @param {!CodeMirror.InputStream} stream Codemirror input stream.
* @param {!Object} state HCL state object.
* @return {(string|boolean)} 'string' or false if not a heredoc string.
*/
function heredocTokenizer(stream, state) {
if (!stream.eat('<')) {
return false;
}
stream.eat('-');

// read rest of line into delim
/** @type {string} */
var delim = '';
while (stream.peek() != null) {
delim += stream.next();
}

state.tokenize = heredocTokenizerFactory(delim);
return 'string';
}

var modeConfig = parserConfig.modeConfig || terraformConfig;
modeConfig.atoms = hclAtoms;
modeConfig.hooks = {
/**
* Consumes double quoted strings.
* @param {!CodeMirror.InputStream} stream Codemirror input stream.
* @param {!Object} state HCL state object.
* @return {string} 'string' token type.
*/
'"': function(stream, state) {
state.tokenize = stringTokenizer;
return state.tokenize(stream, state);
},
/**
* Returns "error" when reading a single quote. The purpose of this is
* to prevent the clike base mode to accept strings in single quotes,
* which is not legal in HCL.
* @param {CodeMirror.InputStream} _ Codemirror input stream.
* @return {string} 'error' token type.
*/
'\'': function(_) {
return 'error';
},
'<': heredocTokenizer,
/**
* Consumes '#' line comments.
* @param {!CodeMirror.InputStream} stream Codemirror input stream.
* @return {string} 'comment' token type.
*/
'#': function(stream) {
stream.skipToEnd();
return 'comment';
},
/**
* Indentation hook. The lack of semicolons confuses the underlying
* "clike" scanner and it interprets the second and following lines as
* continuation of the same "statement", applying additional indent.
* This callback disables this by always returning ctx.indented.
*
* @param {!Object} _ HCL state object.
* @param {!Object} ctx HCL parser context.
* @return {(number|boolean)} number of spaces to indent with or false
* to fall back to clike's default behavior.
*/
'indent': function(_, ctx) {
if (ctx.type == 'statement') {
return ctx.indented;
}
return false
},
};
modeConfig.isPunctuationChar = /[{}\[\],]/;
modeConfig.isOperatorChar = /=/;

/** @type {!CodeMirror.Mode} */
var clikeMode = CodeMirror.getMode(config, modeConfig);

return {
/**
* startState initializes and returns the initial state object.
* @param {number=} basecolumn
* @return {!Object} clike state object
*/
startState: function(basecolumn) {
return clikeMode.startState(basecolumn);
},

/**
* startState initializes and returns the initial state object.
* @param {!CodeMirror.InputStream} stream Codemirror input stream.
* @param {!Object} state HCL state object.
* @return {?string} token type
*/
token: function(stream, state) {
return clikeMode.token(stream, state);
},

/**
* indent returns the number of spaces to indent.
* @param {!Object} state HCL state object.
* @param {?string} textAfter text following the current position.
* @return {number} number of spaces.
*/
indent: function(state, textAfter) {
/* if state.tokenize != null, the scanner is currently within a
* multi-line string. While typing a multi-line string, disable
* indentation. */
if (state.tokenize) {
return 0;
}

return clikeMode.indent(state, textAfter);
},

electricInput: /^\s*[}\]]$/,
closeBrackets: '[]{}',
blockCommentStart: '/*',
blockCommentEnd: '*/',
blockCommentContinue: ' * ',
lineComment: '#',
fold: 'brace'
};
});
CodeMirror.defineMIME('text/x-hcl', {name: 'hcl', modeConfig: hclConfig});
CodeMirror.defineMIME(
'text/x-terraform', {name: 'terraform', modeConfig: terraformConfig});
})();
55 changes: 55 additions & 0 deletions mode/hcl/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<!doctype html>

<title>CodeMirror: HCL mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">

<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="hcl.js"></script>
<style>.CodeMirror { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; }</style>
<div id=nav>
<a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>

<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">HCL</a>
</ul>
</div>

<article>
<h2>HCL mode</h2>
<form>
<textarea id="code">
terraform {
# Backend configuration to use remote state on Google Cloud Storage.
backend "gcs" {
bucket = ""
prefix = "terraform/state"
project = "my-example-project"
}
}

resource "google_compute_instance" "instance-1" {
project = "my-example-project"

name = "instance-1"
machine_type = "n1-standard-1"
zone = "us-central1-a"
}
</textarea>
</form>
<script>
const editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: 'hcl',
});
</script>

<p><strong>MIME types defined:</strong> <code>text/x-hcl</code>, <code>text/x-terraform</code>.</p>
</article>
1 change: 1 addition & 0 deletions mode/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ <h2>Language modes</h2>
<li><a href="handlebars/index.html">Handlebars</a></li>
<li><a href="haskell/index.html">Haskell</a> (<a href="haskell-literate/index.html">Literate</a>)</li>
<li><a href="haxe/index.html">Haxe</a></li>
<li><a href="hcl/index.html">HCL</a></li>
<li><a href="htmlembedded/index.html">HTML embedded</a> (JSP, ASP.NET)</li>
<li><a href="htmlmixed/index.html">HTML mixed-mode</a></li>
<li><a href="http/index.html">HTTP</a></li>
Expand Down
2 changes: 2 additions & 0 deletions mode/meta.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
{name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"]},
{name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"]},
{name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"]},
{name: "HCL", mime: "text/x-hcl", mode: "hcl", ext: ["hcl"]},
{name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"]},
{name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"]},
{name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm", "handlebars", "hbs"], alias: ["xhtml"]},
Expand Down Expand Up @@ -141,6 +142,7 @@
{name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx", "tex"], alias: ["tex"]},
{name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v", "sv", "svh"]},
{name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"]},
{name: "Terraform", mime: "text/x-terraform", mode: "hcl", ext: ["tf"]},
{name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"]},
{name: "TiddlyWiki ", mime: "text/x-tiddlywiki", mode: "tiddlywiki"},
{name: "Tiki wiki", mime: "text/tiki", mode: "tiki"},
Expand Down