Debian Codegraph @

codemirror-legacy-modes/mode/sas.js

raw
1 var words = {};
2 var isDoubleOperatorSym = {
3 eq: 'operator',
4 lt: 'operator',
5 le: 'operator',
6 gt: 'operator',
7 ge: 'operator',
8 "in": 'operator',
9 ne: 'operator',
10 or: 'operator'
11 };
12 var isDoubleOperatorChar = /(<=|>=|!=|<>)/;
13 var isSingleOperatorChar = /[=\(:\),{}.*<>+\-\/^\[\]]/;
14
15 // Takes a string of words separated by spaces and adds them as
16 // keys with the value of the first argument 'style'
17 function define(style, string, context) {
18 if (context) {
19 var split = string.split(' ');
20 for (var i = 0; i < split.length; i++) {
21 words[split[i]] = {style: style, state: context};
22 }
23 }
24 }
25 //datastep
26 define('def', 'stack pgm view source debug nesting nolist', ['inDataStep']);
27 define('def', 'if while until for do do; end end; then else cancel', ['inDataStep']);
28 define('def', 'label format _n_ _error_', ['inDataStep']);
29 define('def', 'ALTER BUFNO BUFSIZE CNTLLEV COMPRESS DLDMGACTION ENCRYPT ENCRYPTKEY EXTENDOBSCOUNTER GENMAX GENNUM INDEX LABEL OBSBUF OUTREP PW PWREQ READ REPEMPTY REPLACE REUSE ROLE SORTEDBY SPILL TOBSNO TYPE WRITE FILECLOSE FIRSTOBS IN OBS POINTOBS WHERE WHEREUP IDXNAME IDXWHERE DROP KEEP RENAME', ['inDataStep']);
30 define('def', 'filevar finfo finv fipname fipnamel fipstate first firstobs floor', ['inDataStep']);
31 define('def', 'varfmt varinfmt varlabel varlen varname varnum varray varrayx vartype verify vformat vformatd vformatdx vformatn vformatnx vformatw vformatwx vformatx vinarray vinarrayx vinformat vinformatd vinformatdx vinformatn vinformatnx vinformatw vinformatwx vinformatx vlabel vlabelx vlength vlengthx vname vnamex vnferr vtype vtypex weekday', ['inDataStep']);
32 define('def', 'zipfips zipname zipnamel zipstate', ['inDataStep']);
33 define('def', 'put putc putn', ['inDataStep']);
34 define('builtin', 'data run', ['inDataStep']);
35
36
37 //proc
38 define('def', 'data', ['inProc']);
39
40 // flow control for macros
41 define('def', '%if %end %end; %else %else; %do %do; %then', ['inMacro']);
42
43 //everywhere
44 define('builtin', 'proc run; quit; libname filename %macro %mend option options', ['ALL']);
45
46 define('def', 'footnote title libname ods', ['ALL']);
47 define('def', '%let %put %global %sysfunc %eval ', ['ALL']);
48 // automatic macro variables http://support.sas.com/documentation/cdl/en/mcrolref/61885/HTML/default/viewer.htm#a003167023.htm
49 define('variable', '&sysbuffr &syscc &syscharwidth &syscmd &sysdate &sysdate9 &sysday &sysdevic &sysdmg &sysdsn &sysencoding &sysenv &syserr &syserrortext &sysfilrc &syshostname &sysindex &sysinfo &sysjobid &syslast &syslckrc &syslibrc &syslogapplname &sysmacroname &sysmenv &sysmsg &sysncpu &sysodspath &sysparm &syspbuff &sysprocessid &sysprocessname &sysprocname &sysrc &sysscp &sysscpl &sysscpl &syssite &sysstartid &sysstartname &systcpiphostname &systime &sysuserid &sysver &sysvlong &sysvlong4 &syswarningtext', ['ALL']);
50
51 //footnote[1-9]? title[1-9]?
52
53 //options statement
54 define('def', 'source2 nosource2 page pageno pagesize', ['ALL']);
55
56 //proc and datastep
57 define('def', '_all_ _character_ _cmd_ _freq_ _i_ _infile_ _last_ _msg_ _null_ _numeric_ _temporary_ _type_ abort abs addr adjrsq airy alpha alter altlog altprint and arcos array arsin as atan attrc attrib attrn authserver autoexec awscontrol awsdef awsmenu awsmenumerge awstitle backward band base betainv between blocksize blshift bnot bor brshift bufno bufsize bxor by byerr byline byte calculated call cards cards4 catcache cbufno cdf ceil center cexist change chisq cinv class cleanup close cnonct cntllev coalesce codegen col collate collin column comamid comaux1 comaux2 comdef compbl compound compress config continue convert cos cosh cpuid create cross crosstab css curobs cv daccdb daccdbsl daccsl daccsyd dacctab dairy datalines datalines4 datejul datepart datetime day dbcslang dbcstype dclose ddfm ddm delete delimiter depdb depdbsl depsl depsyd deptab dequote descending descript design= device dflang dhms dif digamma dim dinfo display distinct dkricond dkrocond dlm dnum do dopen doptname doptnum dread drop dropnote dsname dsnferr echo else emaildlg emailid emailpw emailserver emailsys encrypt end endsas engine eof eov erf erfc error errorcheck errors exist exp fappend fclose fcol fdelete feedback fetch fetchobs fexist fget file fileclose fileexist filefmt filename fileref fmterr fmtsearch fnonct fnote font fontalias fopen foptname foptnum force formatted formchar formdelim formdlim forward fpoint fpos fput fread frewind frlen from fsep fuzz fwrite gaminv gamma getoption getvarc getvarn go goto group gwindow hbar hbound helpenv helploc hms honorappearance hosthelp hostprint hour hpct html hvar ibessel ibr id if index indexc indexw initcmd initstmt inner input inputc inputn inr insert int intck intnx into intrr invaliddata irr is jbessel join juldate keep kentb kurtosis label lag last lbound leave left length levels lgamma lib library libref line linesize link list log log10 log2 logpdf logpmf logsdf lostcard lowcase lrecl ls macro macrogen maps mautosource max maxdec maxr mdy mean measures median memtype merge merror min minute missing missover mlogic mod mode model modify month mopen mort mprint mrecall msglevel msymtabmax mvarsize myy n nest netpv new news nmiss no nobatch nobs nocaps nocardimage nocenter nocharcode nocmdmac nocol nocum nodate nodbcs nodetails nodmr nodms nodmsbatch nodup nodupkey noduplicates noechoauto noequals noerrorabend noexitwindows nofullstimer noicon noimplmac noint nolist noloadlist nomiss nomlogic nomprint nomrecall nomsgcase nomstored nomultenvappl nonotes nonumber noobs noovp nopad nopercent noprint noprintinit normal norow norsasuser nosetinit nosplash nosymbolgen note notes notitle notitles notsorted noverbose noxsync noxwait npv null number numkeys nummousekeys nway obs on open order ordinal otherwise out outer outp= output over ovp p(1 5 10 25 50 75 90 95 99) pad pad2 paired parm parmcards path pathdll pathname pdf peek peekc pfkey pmf point poisson poke position printer probbeta probbnml probchi probf probgam probhypr probit probnegb probnorm probsig probt procleave prt ps pw pwreq qtr quote r ranbin rancau random ranexp rangam range ranks rannor ranpoi rantbl rantri ranuni rcorr read recfm register regr remote remove rename repeat repeated replace resolve retain return reuse reverse rewind right round rsquare rtf rtrace rtraceloc s s2 samploc sasautos sascontrol sasfrscr sasmsg sasmstore sasscript sasuser saving scan sdf second select selection separated seq serror set setcomm setot sign simple sin sinh siteinfo skewness skip sle sls sortedby sortpgm sortseq sortsize soundex spedis splashlocation split spool sqrt start std stderr stdin stfips stimer stname stnamel stop stopover sub subgroup subpopn substr sum sumwgt symbol symbolgen symget symput sysget sysin sysleave sysmsg sysparm sysprint sysprintfont sysprod sysrc system t table tables tan tanh tapeclose tbufsize terminal test then timepart tinv tnonct to today tol tooldef totper transformout translate trantab tranwrd trigamma trim trimn trunc truncover type unformatted uniform union until upcase update user usericon uss validate value var weight when where while wincharset window work workinit workterm write wsum xsync xwait yearcutoff yes yyq min max', ['inDataStep', 'inProc']);
58 define('operator', 'and not ', ['inDataStep', 'inProc']);
59
60 // Main function
61 function tokenize(stream, state) {
62 // Finally advance the stream
63 var ch = stream.next();
64
65 // BLOCKCOMMENT
66 if (ch === '/' && stream.eat('*')) {
67 state.continueComment = true;
68 return "comment";
69 } else if (state.continueComment === true) { // in comment block
70 //comment ends at the beginning of the line
71 if (ch === '*' && stream.peek() === '/') {
72 stream.next();
73 state.continueComment = false;
74 } else if (stream.skipTo('*')) { //comment is potentially later in line
75 stream.skipTo('*');
76 stream.next();
77 if (stream.eat('/'))
78 state.continueComment = false;
79 } else {
80 stream.skipToEnd();
81 }
82 return "comment";
83 }
84
85 if (ch == "*" && stream.column() == stream.indentation()) {
86 stream.skipToEnd()
87 return "comment"
88 }
89
90 // DoubleOperator match
91 var doubleOperator = ch + stream.peek();
92
93 if ((ch === '"' || ch === "'") && !state.continueString) {
94 state.continueString = ch
95 return "string"
96 } else if (state.continueString) {
97 if (state.continueString == ch) {
98 state.continueString = null;
99 } else if (stream.skipTo(state.continueString)) {
100 // quote found on this line
101 stream.next();
102 state.continueString = null;
103 } else {
104 stream.skipToEnd();
105 }
106 return "string";
107 } else if (state.continueString !== null && stream.eol()) {
108 stream.skipTo(state.continueString) || stream.skipToEnd();
109 return "string";
110 } else if (/[\d\.]/.test(ch)) { //find numbers
111 if (ch === ".")
112 stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/);
113 else if (ch === "0")
114 stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);
115 else
116 stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/);
117 return "number";
118 } else if (isDoubleOperatorChar.test(ch + stream.peek())) { // TWO SYMBOL TOKENS
119 stream.next();
120 return "operator";
121 } else if (isDoubleOperatorSym.hasOwnProperty(doubleOperator)) {
122 stream.next();
123 if (stream.peek() === ' ')
124 return isDoubleOperatorSym[doubleOperator.toLowerCase()];
125 } else if (isSingleOperatorChar.test(ch)) { // SINGLE SYMBOL TOKENS
126 return "operator";
127 }
128
129 // Matches one whole word -- even if the word is a character
130 var word;
131 if (stream.match(/[%&;\w]+/, false) != null) {
132 word = ch + stream.match(/[%&;\w]+/, true);
133 if (/&/.test(word)) return 'variable'
134 } else {
135 word = ch;
136 }
137 // the word after DATA PROC or MACRO
138 if (state.nextword) {
139 stream.match(/[\w]+/);
140 // match memname.libname
141 if (stream.peek() === '.') stream.skipTo(' ');
142 state.nextword = false;
143 return 'variableName.special';
144 }
145
146 word = word.toLowerCase()
147 // Are we in a DATA Step?
148 if (state.inDataStep) {
149 if (word === 'run;' || stream.match(/run\s;/)) {
150 state.inDataStep = false;
151 return 'builtin';
152 }
153 // variable formats
154 if ((word) && stream.next() === '.') {
155 //either a format or libname.memname
156 if (/\w/.test(stream.peek())) return 'variableName.special';
157 else return 'variable';
158 }
159 // do we have a DATA Step keyword
160 if (word && words.hasOwnProperty(word) &&
161 (words[word].state.indexOf("inDataStep") !== -1 ||
162 words[word].state.indexOf("ALL") !== -1)) {
163 //backup to the start of the word
164 if (stream.start < stream.pos)
165 stream.backUp(stream.pos - stream.start);
166 //advance the length of the word and return
167 for (var i = 0; i < word.length; ++i) stream.next();
168 return words[word].style;
169 }
170 }
171 // Are we in an Proc statement?
172 if (state.inProc) {
173 if (word === 'run;' || word === 'quit;') {
174 state.inProc = false;
175 return 'builtin';
176 }
177 // do we have a proc keyword
178 if (word && words.hasOwnProperty(word) &&
179 (words[word].state.indexOf("inProc") !== -1 ||
180 words[word].state.indexOf("ALL") !== -1)) {
181 stream.match(/[\w]+/);
182 return words[word].style;
183 }
184 }
185 // Are we in a Macro statement?
186 if (state.inMacro) {
187 if (word === '%mend') {
188 if (stream.peek() === ';') stream.next();
189 state.inMacro = false;
190 return 'builtin';
191 }
192 if (word && words.hasOwnProperty(word) &&
193 (words[word].state.indexOf("inMacro") !== -1 ||
194 words[word].state.indexOf("ALL") !== -1)) {
195 stream.match(/[\w]+/);
196 return words[word].style;
197 }
198
199 return 'atom';
200 }
201 // Do we have Keywords specific words?
202 if (word && words.hasOwnProperty(word)) {
203 // Negates the initial next()
204 stream.backUp(1);
205 // Actually move the stream
206 stream.match(/[\w]+/);
207 if (word === 'data' && /=/.test(stream.peek()) === false) {
208 state.inDataStep = true;
209 state.nextword = true;
210 return 'builtin';
211 }
212 if (word === 'proc') {
213 state.inProc = true;
214 state.nextword = true;
215 return 'builtin';
216 }
217 if (word === '%macro') {
218 state.inMacro = true;
219 state.nextword = true;
220 return 'builtin';
221 }
222 if (/title[1-9]/.test(word)) return 'def';
223
224 if (word === 'footnote') {
225 stream.eat(/[1-9]/);
226 return 'def';
227 }
228
229 // Returns their value as state in the prior define methods
230 if (state.inDataStep === true && words[word].state.indexOf("inDataStep") !== -1)
231 return words[word].style;
232 if (state.inProc === true && words[word].state.indexOf("inProc") !== -1)
233 return words[word].style;
234 if (state.inMacro === true && words[word].state.indexOf("inMacro") !== -1)
235 return words[word].style;
236 if (words[word].state.indexOf("ALL") !== -1)
237 return words[word].style;
238 return null;
239 }
240 // Unrecognized syntax
241 return null;
242 }
243
244 export const sas = {
245 name: "sas",
246 startState: function () {
247 return {
248 inDataStep: false,
249 inProc: false,
250 inMacro: false,
251 nextword: false,
252 continueString: null,
253 continueComment: false
254 };
255 },
256 token: function (stream, state) {
257 // Strip the spaces, but regex will account for them either way
258 if (stream.eatSpace()) return null;
259 // Go through the main process
260 return tokenize(stream, state);
261 },
262
263 languageData: {
264 commentTokens: {block: {open: "/*", close: "*/"}}
265 }
266 };