UNPKG

2.73 kBJavaScriptView Raw
1/* @flow */
2
3// The algorithm used to determine whether a regexp can appear at a
4// given point in the program is loosely based on sweet.js' approach.
5// See https://github.com/mozilla/sweet.js/wiki/design
6
7"use strict";
8
9var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
10
11exports.__esModule = true;
12
13var _types = require("./types");
14
15var TokContext = function TokContext(token /*: string*/, isExpr /*:: ?: boolean*/, preserveSpace /*:: ?: boolean*/, override /*:: ?: Function*/) {
16 _classCallCheck(this, TokContext);
17
18 this.token = token;
19 this.isExpr = !!isExpr;
20 this.preserveSpace = !!preserveSpace;
21 this.override = override;
22};
23
24exports.TokContext = TokContext;
25var types = {
26 b_stat: new TokContext("{", false),
27 b_expr: new TokContext("{", true),
28 b_tmpl: new TokContext("${", true),
29 p_stat: new TokContext("(", false),
30 p_expr: new TokContext("(", true),
31 q_tmpl: new TokContext("`", true, true, function (p) {
32 return p.readTmplToken();
33 }),
34 f_expr: new TokContext("function", true)
35};
36
37exports.types = types;
38// Token-specific context update code
39
40_types.types.parenR.updateContext = _types.types.braceR.updateContext = function () {
41 if (this.state.context.length === 1) {
42 this.state.exprAllowed = true;
43 return;
44 }
45
46 var out = this.state.context.pop();
47 if (out === types.b_stat && this.curContext() === types.f_expr) {
48 this.state.context.pop();
49 this.state.exprAllowed = false;
50 } else if (out === types.b_tmpl) {
51 this.state.exprAllowed = true;
52 } else {
53 this.state.exprAllowed = !out.isExpr;
54 }
55};
56
57_types.types.braceL.updateContext = function (prevType) {
58 this.state.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
59 this.state.exprAllowed = true;
60};
61
62_types.types.dollarBraceL.updateContext = function () {
63 this.state.context.push(types.b_tmpl);
64 this.state.exprAllowed = true;
65};
66
67_types.types.parenL.updateContext = function (prevType) {
68 var statementParens = prevType === _types.types._if || prevType === _types.types._for || prevType === _types.types._with || prevType === _types.types._while;
69 this.state.context.push(statementParens ? types.p_stat : types.p_expr);
70 this.state.exprAllowed = true;
71};
72
73_types.types.incDec.updateContext = function () {
74 // tokExprAllowed stays unchanged
75};
76
77_types.types._function.updateContext = function () {
78 if (this.curContext() !== types.b_stat) {
79 this.state.context.push(types.f_expr);
80 }
81
82 this.state.exprAllowed = false;
83};
84
85_types.types.backQuote.updateContext = function () {
86 if (this.curContext() === types.q_tmpl) {
87 this.state.context.pop();
88 } else {
89 this.state.context.push(types.q_tmpl);
90 }
91 this.state.exprAllowed = false;
92};
\No newline at end of file