-
-
Notifications
You must be signed in to change notification settings - Fork 236
Writing a Code Generator
Jos Ahrens edited this page Jun 25, 2017
·
4 revisions
Your code generator file is just a simple react component. An example can be found below.
Please note that your code generator must handle all the possible cases:
- Non-global match
- Global match
- Non-global substitution
- Global substitution
-
x-mode (this is when a regex can span multiple lines)
You can experiment with the existing flavors to ensure that yours fulfills all cases.
class MyNewLanguage extends PureComponent {
//
// Proptypes
static propTypes = {
regex: PropTypes.string.isRequired,
flags: PropTypes.string.isRequired,
delimiter: PropTypes.string.isRequired,
testString: PropTypes.string.isRequired,
isSubstituting: PropTypes.bool.isRequired,
isGlobal: PropTypes.bool.isRequired,
substString: PropTypes.string
};
//
// Control
// If you need to manipulate any data, you should preferably do it in a function defined
// on the class body here. This could for example be sanitizing data (escaping quotes, etc).
//
// Render functions
render() {
return (
<Highlight lang="myNewLanguage">
{this._renderCode()}
</Highlight>
);
}
_renderCode() {
const { regex, flags, delimiter, testString, isSubstituting, substString, isGlobal } = this.props;
const codeString = new CodeString();
// CodeString is a basic class that allows you to create a code snippet without having
// to worry about indentation or newlines.
// The only functions are `append`, `indent` and `toString`.
// The implementation can be found on this page.
// Create your code string here
codeString.append(`Use string literals when ${regex} interpolating ${flags} data`);
return codeString.toString();
}
}
export default MyNewLangauge;class CodeString {
constructor(string = '') {
this.string = string;
this.indentLevel = 0;
}
indent(str, space = 0) {
return ' '.repeat(space) + str;
}
append(str = '', indentLevel) {
this.string += this.indent(`${str}\n`, this.indentLevel);
// If `indentLevel` is defined, it will be set until changed later.
if (indentLevel != null) {
this.indentLevel = indentLevel;
}
}
toString() {
return this.string;
}
}
export default CodeString;