1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! This module provides `handle_body` (and internally `handle_item`),
//! that does most of the work for [`crate::input::Context::transform`].

use super::cssdest::CssDestination;
use super::CssData;
use crate::css::{self, AtRule, Import};
use crate::error::ResultPos;
use crate::input::{Context, Loader, Parsed, SourceKind};
use crate::sass::{get_global_module, Expose, Item, UseAs};
use crate::value::ValueRange;
use crate::{Error, Invalid, ScopeRef};

pub fn handle_parsed(
    items: Parsed,
    dest: &mut dyn CssDestination,
    scope: ScopeRef,
    file_context: &mut Context<impl Loader>,
) -> Result<(), Error> {
    match items {
        Parsed::Scss(items) => handle_body(&items, dest, scope, file_context),
        Parsed::Css(items) => push_items(dest, items).no_pos(),
    }
}

fn handle_body(
    items: &[Item],
    dest: &mut dyn CssDestination,
    scope: ScopeRef,
    file_context: &mut Context<impl Loader>,
) -> Result<(), Error> {
    for b in items {
        handle_item(b, dest, scope.clone(), file_context)?;
    }
    Ok(())
}

fn handle_item(
    item: &Item,
    dest: &mut dyn CssDestination,
    scope: ScopeRef,
    file_context: &mut Context<impl Loader>,
) -> Result<(), Error> {
    match item {
        Item::Use(ref name, ref as_n, ref with, ref pos) => {
            let name = name.evaluate(scope.clone())?.take_value();
            let module = if let Some(module) = get_global_module(&name) {
                if !with.is_empty() {
                    return Err(Invalid::ConfigBuiltin).at(pos);
                }
                module
            } else if let Some(sourcefile) =
                file_context.find_file(&name, SourceKind::Use(pos.clone()))?
            {
                let module = dest.head().load_module(
                    sourcefile.path(),
                    |dest| {
                        let module = ScopeRef::new_global(scope.get_format());
                        for (name, value, default) in with {
                            let default = if *default {
                                scope.get_or_none(name)
                            } else {
                                None
                            };
                            let value = default.ok_or(()).or_else(|()| {
                                value.do_evaluate(scope.clone(), true)
                            })?;
                            if module.get_or_none(name).is_none() {
                                module.define(name.clone(), value)?;
                            } else {
                                return Err(Error::error(
                                    "The same variable may only be configured once.",
                                ));
                            }
                        }
                        handle_parsed(
                            sourcefile.parse()?,
                            dest,
                            module.clone(),
                            file_context,
                        )?;
                        Ok(module)
                    })?;
                file_context.unlock_loading(&sourcefile);
                module
            } else {
                return Err(Error::BadCall(
                    "Can't find stylesheet to import.".into(),
                    pos.clone(),
                    None,
                ));
            };
            scope.do_use(module, &name, as_n, &Expose::All)?;
        }
        Item::Forward(ref name, ref as_n, ref expose, ref with, ref pos) => {
            let name = name.evaluate(scope.clone())?.take_value();
            let module = if let Some(module) = get_global_module(&name) {
                if !with.is_empty() {
                    return Err(Invalid::ConfigBuiltin).at(pos);
                }
                module
            } else if let Some(sourcefile) = file_context
                .find_file(&name, SourceKind::Forward(pos.clone()))?
            {
                let module = dest.head().load_module(
                    sourcefile.path(),
                    |dest| {
                        let module = ScopeRef::new_global(scope.get_format());
                        for (name, value, default) in with {
                            let default = if *default {
                                scope.get_or_none(name)
                            } else {
                                None
                            };
                            let value = default.ok_or(()).or_else(|()| {
                                value.do_evaluate(scope.clone(), true)
                            })?;
                            if module.get_or_none(name).is_none() {
                                module.define(name.clone(), value)?;
                            } else {
                                return Err(Error::error(
                                    "The same variable may only be configured once.",
                                ));
                            }
                        }
                        handle_parsed(
                            sourcefile.parse()?,
                            dest,
                            module.clone(),
                            file_context,
                        )?;
                        Ok(module)
                    });
                file_context.unlock_loading(&sourcefile);
                module?
            } else {
                return Err(Error::S(format!("Module {} not found", name)));
            };
            scope.forward().do_use(module, &name, as_n, expose)?;
        }
        Item::Import(ref names, ref args, ref pos) => {
            'name: for name in names {
                let name = name.evaluate(scope.clone())?;
                if args.is_null() {
                    let x = name.value();
                    if let Some(sourcefile) = file_context
                        .find_file(x, SourceKind::Import(pos.clone()))?
                    {
                        match sourcefile.parse()? {
                            Parsed::Scss(items) => {
                                let mut thead = CssData::new();
                                let module = ScopeRef::sub(scope.clone());
                                let selectors = scope.get_selectors();
                                if !selectors.is_root() {
                                    let mut rule = thead
                                        .start_rule(selectors.clone())
                                        .at(pos)?;
                                    handle_body(
                                        &items,
                                        &mut rule,
                                        module.clone(),
                                        file_context,
                                    )?;
                                } else {
                                    handle_body(
                                        &items,
                                        &mut thead,
                                        module.clone(),
                                        file_context,
                                    )?;
                                }
                                push_items(dest, thead.into_iter())
                                    .at(pos)?;
                                scope.do_use(
                                    module,
                                    "",
                                    &UseAs::Star,
                                    &Expose::All,
                                )?;
                            }
                            Parsed::Css(items) => {
                                push_items(dest, items).at(pos)?
                            }
                        }
                        file_context.unlock_loading(&sourcefile);
                        continue 'name;
                    }
                    if !(x.starts_with("http://")
                        || x.starts_with("https://")
                        || x.starts_with("//")
                        || x.ends_with(".css")
                        || name.is_css_url())
                    {
                        return Err(Error::BadCall(
                            "Can't find stylesheet to import.".into(),
                            pos.clone(),
                            None,
                        ));
                    }
                }
                let args = args.evaluate(scope.clone())?;
                dest.push_import(Import::new(name, args));
            }
        }
        Item::AtRoot(ref selectors, ref body) => {
            let selectors = selectors
                .eval(scope.clone())?
                .with_backref(scope.get_selectors().one());
            let subscope = ScopeRef::sub_selectors(scope, selectors.clone());
            if !selectors.is_root() {
                let mut rule = dest.start_rule(selectors).no_pos()?;
                handle_body(body, &mut rule, subscope, file_context)?;
            } else {
                handle_body(body, dest, subscope, file_context)?;
            }
        }
        Item::AtRule {
            name,
            args,
            body,
            pos,
        } => {
            let name = name.evaluate(scope.clone())?.take_value();
            let args = args.evaluate(scope.clone())?;
            if let Some(ref body) = *body {
                let mut atrule = dest.start_atrule(name, args);
                let local = ScopeRef::sub(scope);
                handle_body(body, &mut atrule, local, file_context)?;
            } else {
                dest.push_item(AtRule::new(name, args, None).into())
                    .at(pos)?;
            }
        }
        Item::VariableDeclaration(ref var) => {
            var.evaluate(&scope)?;
        }
        Item::FunctionDeclaration(ref name, ref body) => {
            if name == "calc"
                || name == "element"
                || name == "expression"
                || name == "url"
            {
                // Ok, this is cheating for the test suite ...
                let p = body.decl.clone().opt_back("@function ");
                return Err(Invalid::FunctionName.at(p));
            }
            check_body(&body.body, BodyContext::Function)?;
            scope.define_function(name.into(), body.closure(&scope).into());
        }
        Item::Return(_, ref pos) => {
            return Err(Invalid::AtRule.at(pos.clone()));
        }

        Item::MixinDeclaration(ref name, ref body) => {
            check_body(&body.body, BodyContext::Mixin)?;
            scope.define_mixin(name.into(), body.closure(&scope).into())
        }
        Item::MixinCall(ref name, ref args, ref body, ref pos) => {
            if let Some(mixin) = scope.get_mixin(&name.into()) {
                let mixin = mixin
                    .get(scope.clone(), args, pos, file_context)
                    .map_err(|e| e.called_from(pos, name))?;
                mixin.define_content(&scope, body);
                handle_parsed(mixin.body, dest, mixin.scope, file_context)
                    .map_err(|e: Error| match e {
                        Error::Invalid(err, _) => err.at(pos.clone()),
                        Error::BadCall(msg, pos, p2) => {
                            Error::BadCall(msg, pos.in_call(name), p2)
                        }
                        e => {
                            let pos = pos.in_call(name);
                            Error::BadCall(format!("{:?}", e), pos, None)
                        }
                    })?;
            } else {
                return Err(Error::BadCall(
                    "Undefined mixin.".into(),
                    pos.clone(),
                    None,
                ));
            }
        }
        Item::Content(args, pos) => {
            if let Some(content) = scope.get_content() {
                let mixin = content
                    .get(scope, args, pos, file_context)
                    .map_err(|e| e.called_from(pos, "@content"))?;
                handle_parsed(mixin.body, dest, mixin.scope, file_context)?;
            }
        }

        Item::IfStatement(ref cond, ref do_if, ref do_else) => {
            let cond = cond.evaluate(scope.clone())?.is_true();
            let items = if cond { do_if } else { do_else };
            check_body(items, BodyContext::Control)?;
            handle_body(items, dest, scope, file_context)?;
        }
        Item::Each(ref names, ref values, ref body) => {
            check_body(body, BodyContext::Control)?;
            let pushed = scope.store_local_values(names);
            for value in values.evaluate(scope.clone())?.iter_items() {
                scope.define_multi(names, value)?;
                handle_body(body, dest, scope.clone(), file_context)?;
            }
            scope.restore_local_values(pushed);
        }
        Item::For {
            ref name,
            ref from,
            ref to,
            inclusive,
            ref body,
        } => {
            let range = ValueRange::new(
                from.evaluate(scope.clone())?,
                to.evaluate(scope.clone())?,
                *inclusive,
            )?;
            check_body(body, BodyContext::Control)?;
            for value in range {
                let scope = ScopeRef::sub(scope.clone());
                scope.define(name.clone(), value)?;
                handle_body(body, dest, scope, file_context)?;
            }
        }
        Item::While(ref cond, ref body) => {
            check_body(body, BodyContext::Control)?;
            let scope = ScopeRef::sub(scope);
            while cond.evaluate(scope.clone())?.is_true() {
                handle_body(body, dest, scope.clone(), file_context)?;
            }
        }

        Item::Debug(ref value) => {
            eprintln!("DEBUG: {}", value.evaluate(scope)?.introspect())
        }
        Item::Warn(ref value) => {
            eprintln!("WARNING: {}", value.evaluate(scope)?.introspect());
        }
        Item::Error(ref value, ref pos) => {
            let msg = value.evaluate(scope)?.introspect().to_string();
            return Err(Invalid::AtError(msg).at(pos.clone()));
        }

        Item::Rule(ref selectors, ref body) => {
            check_body(body, BodyContext::Rule)?;
            let selectors =
                selectors.eval(scope.clone())?.inside(scope.get_selectors());
            let mut dest = dest.start_rule(selectors.clone()).no_pos()?;
            let scope = ScopeRef::sub_selectors(scope, selectors);
            handle_body(body, &mut dest, scope, file_context)?;
        }
        Item::Property(ref name, ref value, ref pos) => {
            let v = value.evaluate(scope.clone())?;
            if !v.is_null() {
                let name = name.evaluate(scope)?.take_value();
                // Note: inner pos here is correctly the value pos,
                // but the outher should probably be the entire property.
                dest.push_property(name, v.valid_css().at(pos)?).at(pos)?;
            }
        }
        Item::CustomProperty(ref name, ref value) => {
            let v = value.evaluate(scope.clone())?;
            if !v.is_null() {
                let name = name.evaluate(scope)?.take_value();
                dest.push_custom_property(name, v).no_pos()?;
            }
        }
        Item::NamespaceRule(ref name, ref value, ref body) => {
            check_body(body, BodyContext::NsRule)?;
            let value = value.evaluate(scope.clone())?;
            let name = name.evaluate(scope.clone())?.take_value();
            if !value.is_null() {
                dest.push_property(name.clone(), value).no_pos()?;
            }
            let mut dest = dest.start_nsrule(name).no_pos()?;
            handle_body(body, &mut dest, scope, file_context)?;
        }
        Item::Comment(ref c) => {
            if !scope.get_format().is_compressed() {
                dest.push_comment(c.evaluate(scope)?.take_value().into());
            }
        }
        Item::None => (),
    }
    Ok(())
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum BodyContext {
    Mixin,
    Function,
    Control,
    Rule,
    NsRule,
}

fn check_body(body: &[Item], context: BodyContext) -> Result<(), Error> {
    for item in body {
        match item {
            Item::Forward(_, _, _, _, pos) => {
                return Err(Invalid::AtRule.at(pos.clone()));
            }
            Item::Use(_, _, _, pos) => {
                return Err(Invalid::AtRule.at(pos.clone()));
            }
            Item::MixinDeclaration(.., ref decl) => {
                let pos = decl.decl.clone().opt_back("@mixin ");
                match context {
                    BodyContext::Mixin => {
                        return Err(Invalid::MixinInMixin.at(pos));
                    }
                    BodyContext::Control => {
                        return Err(Invalid::MixinInControl.at(pos));
                    }
                    BodyContext::Rule => (), // This is ok
                    _ => {
                        return Err(Invalid::AtRule.at(pos.opt_trail_ws()));
                    }
                }
            }
            Item::FunctionDeclaration(_, ref body) => {
                let pos = body.decl.clone().opt_back("@function ");
                match context {
                    BodyContext::Mixin => {
                        return Err(Invalid::FunctionInMixin.at(pos));
                    }
                    BodyContext::Control => {
                        return Err(Invalid::FunctionInControl.at(pos));
                    }
                    BodyContext::Rule => (), // This is ok
                    _ => {
                        return Err(Invalid::AtRule.at(pos.opt_trail_ws()));
                    }
                }
            }
            Item::Return(_, ref pos) if context != BodyContext::Function => {
                return Err(Invalid::AtRule.at(pos.clone()));
            }
            Item::AtRule {
                name,
                args: _,
                body: _,
                pos,
            } if context != BodyContext::Rule => {
                if !name
                    .single_raw()
                    .map(|name| CSS_AT_RULES.contains(&name))
                    .unwrap_or(false)
                {
                    return Err(Invalid::AtRule.at(pos.clone()));
                }
            }
            _ => (),
        }
    }
    Ok(())
}

const CSS_AT_RULES: [&str; 16] = [
    "charset",
    "color-profile",
    "counter-style",
    "document",
    "font-face",
    "font-feature-values",
    "import",
    "keyframes",
    "layer",
    "media",
    "namespace",
    "page",
    "property",
    "scroll-timeline",
    "supports",
    "viewport",
];

fn push_items(
    dest: &mut dyn CssDestination,
    items: impl IntoIterator<Item = css::Item>,
) -> Result<(), Invalid> {
    for item in items {
        dest.push_item(item)?;
    }
    Ok(())
}